import java.applet.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class RubberBand extends JPanel { int cursorX = -1; int cursorY = -1; int orignX = -1; int orignY = -1; public RubberBand() { addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { //Draw a line ending at current //cursor position. cursorX = e.getX(); cursorY = e.getY(); repaint(); } }); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { //Set orign of line to current //cursor position. orignX = e.getX(); orignY = e.getY(); } }); } public void paintComponent(Graphics g) { //This is were drawing is done. Do not touch the paint //method. //Call super or the panels background will not //be redrawn. super.paintComponent( g ); //Draw the line where the user has placed it. if (cursorX != -1 && cursorY != -1 && orignX != -1 && orignY != -1) g.drawLine(orignX, orignY, cursorX, cursorY); } public static void main(String[] args) { JFrame f = new JFrame("simple rubberband"); f.getContentPane().add(new RubberBand(), BorderLayout.CENTER); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } }); f.setSize(300, 300); f.setVisible(true); } }