// Java Scribble Applet: with event handling using nested, adapter, and disembodied classes import java.io.*; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; public class Scribble4 extends JApplet { int last_x=0; int last_y=0; Color current_color=Color.black; JButton clear_button; 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 (new MouseMotionAdapter () { public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); Graphics g = getGraphics(); g.setColor(current_color); g.drawLine(last_x,last_y, x,y); last_x = x; last_y = y; } } ); addMouseListener(new MouseAdapter () { public void mousePressed(MouseEvent e) { last_x = e.getX(); last_y = e.getY(); } } ); event_handler ev = new event_handler(); clear_button.addActionListener(ev); color_choices.addActionListener(ev); } class event_handler implements ActionListener { // 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 height = c.getInsets().right - c.getInsets().left; int width = 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; } } } private void write_error (String x) { Graphics g = this.getGraphics(); g.drawString(x, 100, 100); } }