// File: TestApplet.java (Module 9) // // Author: Rahul Simha // Created: October 21, 1998 // // Panels and canvases - in an applet. import java.awt.*; import java.awt.event.*; import java.applet.*; public class TestApplet extends Applet implements ActionListener, MouseListener { // Data. Button quitb, clearb, startb; Canvas c; Panel p; boolean start = false; // Constructor. public void init() { // Title and size cannot be set in an applet. this.setBackground (Color.cyan); // 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); // Default for an applet is FlowLayout. 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 (); p.setLayout (new FlowLayout()); // 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 "TestApplet"