// File: TestAwt25.java (Module 9) // // Author: Rahul Simha // Created: October 21, 1998 // // Panels and canvases - multiple panels. import java.awt.*; import java.awt.event.*; // Needed for ActionListener. class NewFrame extends Frame implements ActionListener, MouseListener { // Data. Button quitb, clearb, startb; Canvas c; Panel p; boolean start = false; // 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); // Create a quit button. quitb = new Button ("Quit"); quitb.setBackground (Color.red); quitb.setFont (new Font ("Serif", Font.PLAIN | Font.BOLD, 15)); quitb.addActionListener (this); // this.setLayout (new BorderLayout()); this.add (quitb, BorderLayout.SOUTH); // Create a white canvas. c = new Canvas (); c.setBackground (Color.white); c.setForeground (Color.blue); c.addMouseListener (this); // Add canvas to frame in the center. this.add (c, BorderLayout.CENTER); // Create a Panel p = new Panel (); // Create GridLayout with one row and two columns: p.setLayout (new GridLayout(1,2)); // Create a clear button. clearb = new Button ("Clear"); clearb.addActionListener (this); clearb.setBackground (Color.green); // Create a start button. startb = new Button ("Start"); startb.addActionListener (this); startb.setBackground (Color.green); // Add start and clear buttons to panel. p.add (clearb); p.add (startb); // Now add the panel to the frame. this.add (p, BorderLayout.NORTH); // Show the frame. this.setVisible (true); } // This method is required to implement the // ActionListener interface. public void actionPerformed (ActionEvent a) { String s = a.getActionCommand(); if (s.equalsIgnoreCase ("Quit")) System.exit(0); else if (s.equalsIgnoreCase ("Clear")) { // Note: must call repaint() of canvas // to reset the background. c.setBackground (Color.white); c.repaint (); current_x = current_y = 0; } else if (s.equalsIgnoreCase ("Start")) start = true; } int current_x=0, current_y=0; // These methods are required to implement // the MouseListener interface. public void mouseClicked (MouseEvent m) { if (!start) // User must click start once to draw. return; 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; } // We need to implement these methods, but // don't actually have to do anything inside. public void mouseEntered (MouseEvent m) {} public void mouseExited (MouseEvent m) {} public void mousePressed (MouseEvent m) {} public void mouseReleased (MouseEvent m) {} } // End of class "NewFrame" public class TestAwt25 { public static void main (String[] argv) { NewFrame nf = new NewFrame (300, 200); } }