import java.awt.*; import java.awt.event.*; // for ActionListener, MouseListener import javax.swing.*; public class SimpleMouseExample // used to draw lines between point where mouse is pressed and point where mouse is released { public static void main(String[] args) { JFrame frame=new JFrame("simple button example"); frame.setSize(500,500); MouseExample p=new MouseExample(); frame.add(p); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static class MouseExample extends JPanel implements ActionListener, MouseListener // ActionListener for 1 JButton { private int x1, y1, x2, y2; // X,Y coordinate of latest Mouse Event private boolean clear; // boolean used to determine whether to clear the Graphics object or not public MouseExample() { x1=x2=y1=y2=-1; // no current coordinate, set it to some off-the-screen value JButton reset=new JButton("Reset Drawing"); // JButton to change clear from false to true to clear the Graphics object reset.addActionListener(this); // use this class to implement this JButton's ActionListener add(reset); // add the JButton to this JPanel addMouseListener(this); // add a MouseListener to this class clear=false; // clear indicates whether the reset the Graphics object, currently false } public void actionPerformed(ActionEvent e) { clear=true; // upon JButton click, reset clear to true and repaint repaint(); } public void mouseClicked(MouseEvent e) {} // we only need to implement mousePressed and mouseReleased, these others public void mouseEntered(MouseEvent e) {} // have to be here to implement MouseListener but we don't need code for them public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) // upon mousePressed, remember the x,y coordinate which will be the start of our line { x1=e.getX(); y1=e.getY(); } public void mouseReleased(MouseEvent e) // upon mouseReleased, get the x,y coordinate and call repaint to draw a line { // from x,y coordinates when mousePressed to these x,y coordinates x2=e.getX(); y2=e.getY(); repaint(); } public void paintComponent(Graphics g) // either clear the Graphics image (super.paintComponent(g)) or draw a line { if(clear) // upon clear, clear the Graphics image and reset clear to false { clear=false; super.paintComponent(g); } else g.drawLine(x1,y1,x2,y2); // upon !clear, draw the line } } }