import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; /** * Ex2 -- a JFrame with a canvas * * @author rpj * @version 29xii06 */ public class Ex2 extends JFrame { // constants private static final int SIZE = 400; private int lastX, lastY; private JButton clear; private ScribbleCanvas c; private Graphics g; /** * Constructor for objects of class Ex2 */ public Ex2() { setTitle("Scribble frame"); setSize(SIZE,SIZE); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = getContentPane(); pane.setLayout(new BorderLayout()); clear = new JButton("clear"); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { c.reset(); } }); pane.add(clear, BorderLayout.SOUTH); c = new ScribbleCanvas(); c.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { lastX = e.getX(); lastY = e.getY(); } }); // Define, instantiate and register a MouseMotionListener object. c.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { int x = e.getX(), y = e.getY(); c.add(new Segment(lastX, lastY, x, y)); lastX = x; lastY = y; } }); pane.add(c, BorderLayout.CENTER); validate(); } /** * main * * @param args the commandline arguments */ public static void main(String[] args) { Ex2 foo = new Ex2(); } } class Segment { private int x1, y1, x2, y2; public Segment(int a, int b, int c, int d) { x1 = a; y1 = b; x2 = c; y2 = d; } public void draw(Graphics g) { g.drawLine(x1, y1, x2, y2); } } class ScribbleCanvas extends Canvas { private Vector segments; public ScribbleCanvas() { segments = new Vector(); } public void reset() { segments.removeAllElements(); repaint(); } public void add (Segment s) { segments.add(s); repaint(); } public void paint(Graphics g) { for (Segment s : segments) { s.draw(g); } } }