// File: TestApplet.java (Module 9b) // // Author: Rahul Simha // Created: October 21, 2000 // // Panels - in an applet. import java.awt.*; import java.awt.event.*; import java.applet.*; public class TestApplet extends Applet implements ActionListener, MouseListener { // Data. Button quitB, orangeB, greenB; Panel p; Canvas c; int currentX = 0, currentY = 0; Color currentColor = Color.green; // Applet's equivalent of constructor. public void init() { // Title and size cannot be set in an applet. this.setBackground (Color.cyan); // Create a quit button: using AWT's 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 using java.awt.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()); p.setBackground (Color.white); // Create a clear button. orangeB = new Button ("Orange"); orangeB.addActionListener (this); orangeB.setBackground (Color.orange); // Create a start button. greenB = new Button ("Green"); greenB.addActionListener (this); greenB.setBackground (Color.green); // Add start and clear buttons to panel. p.add (orangeB); p.add (greenB); // 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 ("Orange")) { currentColor = Color.orange; } else if (s.equalsIgnoreCase ("Green")) { currentColor = Color.green; } } // These methods are required to implement // the MouseListener interface. public void mouseClicked (MouseEvent m) { int x = m.getX(); int y = m.getY(); Graphics g = c.getGraphics(); g.setColor (currentColor); g.drawLine (currentX, currentY, x, y); currentX = x; currentY = 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"