import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*; class Lines2 extends JComponent implements MouseInputListener { public static void main (String[] args) { JFrame gui = new JFrame ("Demo"); gui.setContentPane (new Lines2 ()); gui.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); gui.pack (); gui.setVisible (true); } Lines2 () { lines = new ArrayList (); setPreferredSize (new Dimension (400, 400)); addMouseListener (this); addMouseMotionListener (this); cx = cy = -1; } public synchronized void paintComponent (Graphics g) { g.setColor (Color.white); g.fillRect (0, 0, 400, 400); int x, y; x = y = 200; int i; for (i = 0; i < lines.size (); i += 1) { Point p = (Point) lines.get (i); g.setColor (new Color (i*217 % 255, i * 101 % 255, i * 17 % 255)); g.drawLine (x, y, p.x, p.y); x = p.x; y = p.y; } if (cx != -1 && cy != -1) { g.setColor (new Color (i*217 % 255, i * 101 % 255, i * 17 % 255)); g.drawLine (x, y, cx, cy); } } private java.util.List lines; private int cx, cy; synchronized void add (int x, int y) { lines.add (new Point (x, y)); repaint (); } public void mouseClicked (MouseEvent e) { add (e.getX (), e.getY ()); } public void mouseMoved (MouseEvent e) { cx = e.getX (); cy = e.getY (); repaint (); } public void mouseEntered (MouseEvent e) { } public void mouseExited (MouseEvent e) { cx = cy = -1; repaint (); } public void mousePressed (MouseEvent e) { } public void mouseReleased (MouseEvent e) { } public void mouseDragged (MouseEvent e) { } }