// Example of Java Applet using Swing Classes : centralized event handling import java.io.*; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; public class Scribble extends JApplet implements ActionListener, MouseListener, MouseMotionListener { private int last_x=0; private int last_y=0; private Color current_color=Color.black; private JButton clear_button; private JComboBox color_choices; public void init () { Container c = getContentPane(); c.setLayout(new FlowLayout()); clear_button = new JButton("Clear"); clear_button.setForeground(Color.black); clear_button.setBackground(Color.gray); c.add(clear_button); color_choices = new JComboBox(); color_choices.addItem("black"); color_choices.addItem("red"); color_choices.addItem("yellow"); color_choices.addItem("green"); color_choices.addItem("blue"); color_choices.addItem("cyan"); color_choices.setForeground(Color.black); color_choices.setBackground(Color.lightGray); c.add(new Label("Color:")); c.add(color_choices); // addMouseMotionListener(this); // addMouseListener(this); clear_button.addActionListener(this); color_choices.addActionListener(this); } private void write_error (String x) { Graphics g = this.getGraphics(); g.drawString(x, 100, 100); } // implements the ActionListener interface (the only method in // the ActionListener interface) public void actionPerformed (ActionEvent evt) { if (evt.getSource() == clear_button){ System.err.println("clear clicked..."); Container c = getContentPane(); Graphics g = c.getGraphics(); // Rectangle r = this.bounds(); g.setColor(c.getBackground()); int width = c.getInsets().right - c.getInsets().left; int height = c.getInsets().bottom - c.getInsets().top; System.err.println("height: " + c.getHeight() + " width: " + c.getWidth()); g.fillRect(0, 0, c.getHeight(), c.getWidth()); } else if (evt.getSource() == color_choices){ String arg = (String)(((JComboBox)evt.getSource()).getSelectedItem()); if (arg.equals("black")) current_color = Color.black; else if (arg.equals("red")) current_color = Color.red; else if (arg.equals("yellow")) current_color = Color.yellow; else if (arg.equals("green")) current_color = Color.green; else if (arg.equals("blue")) current_color = Color.blue; else if (arg.equals("cyan")) current_color = Color.cyan; } } // MouseListener interface public void mousePressed(MouseEvent e) { last_x = e.getX(); last_y = e.getY(); } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) {} // MouseMovementListener interface (do nothing methods MUST be defined) public void mouseMoved (MouseEvent ev) {} public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); Graphics g = this.getGraphics(); g.setColor(current_color); g.drawLine(last_x,last_y, x,y); last_x = x; last_y = y; } }