// File: OneCanvas.java (Module 10) // // Author: Rahul Simha // Created: November 2, 1998 // // A single canvas import java.awt.*; import java.awt.event.*; // Needed for ActionListener. class NewFrame extends Frame { // Data. int current_x=0, current_y=0; Canvas c; // Constructor. public NewFrame (int width, int height) { // Set the title and other frame parameters. this.setTitle ("Panel and canvas example"); this.setResizable (true); this.setBackground (Color.cyan); this.setSize (width, height); // this.setLayout (new BorderLayout()); // Create a quit button. Button quitb = new Button ("Quit"); quitb.setBackground (Color.red); quitb.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); // Using an anonymous class: quitb.addActionListener ( new ActionListener() { public void actionPerformed (ActionEvent a) { System.exit(0); } } ); this.add (quitb, BorderLayout.SOUTH); // Create a white canvas. c = new Canvas (); c.setBackground (Color.white); c.setForeground (Color.blue); // Using an anonymous class: c.addMouseListener ( new MouseAdapter () { public void mouseClicked (MouseEvent m) { int x = m.getX(); int y = m.getY(); Graphics g = c.getGraphics(); g.drawLine (current_x, current_y, x, y); current_x = x; current_y = y; } } ); // Add canvas to frame in the center. this.add (c, BorderLayout.CENTER); // Create a Panel Panel p = new Panel (); p.setLayout (new FlowLayout()); // Create a clear button. Button clearb = new Button ("Clear"); clearb.setBackground (Color.green); // Using an anonymous class: clearb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { c.setBackground (Color.white); c.repaint(); current_x = current_y = 0; } } ); p.add (clearb); // Now add the panel to the frame. this.add (p, BorderLayout.NORTH); // Show the frame. this.setVisible (true); } } // End of class "NewFrame" public class OneCanvas { public static void main (String[] argv) { NewFrame nf = new NewFrame (300, 200); } }