import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /*********************************************************************** ColorMenu is a subclass of the Scrib Applet that adds a menu for selecting color. ************************************************************************/ public class ColorMenu extends Scrib { /* Inner class ColorEntry. Represents info we need for one drawing color */ class ColorEntry { String name; // name to be displayed in menu Color color; // color value for menu selection ColorEntry(String s, Color c) { name = s; color = c; } } /* State variables */ JComboBox<String> colorChoices; JLabel colorLabel; ColorEntry[] colorArray = { new ColorEntry("black", Color.black), new ColorEntry("blue", Color.blue), new ColorEntry("red", Color.red), new ColorEntry("green", Color.green) }; Color currentColor; // current drawing color /* Methods */ public void init() { super.init(); colorChoices = new JComboBox<String>(); colorChoices.addItemListener(new ColorChoiceAdapter()); colorChoices.setForeground(Color.black); colorChoices.setBackground(Color.lightGray); for (int i = 0; i < colorArray.length; i++) colorChoices.addItem(colorArray[i].name); colorLabel = new JLabel(" Color:"); cPane.add(colorLabel); cPane.add(colorChoices); /* replace monochrome mouse motion adapter with a color one */ this.removeMouseMotionListener(mouseMotionAdapt); mouseMotionAdapt = new ColorMouseMotionAdapter(); this.addMouseMotionListener(mouseMotionAdapt); currentColor = colorArray[0].color; } /* Adapter classes for events */ class ColorChoiceAdapter implements ItemListener { public void itemStateChanged(ItemEvent e) { currentColor = colorArray[colorChoices.getSelectedIndex()].color; } } class ColorMouseMotionAdapter implements MouseMotionListener { public void mouseDragged(MouseEvent e) { int x = e.getX(), y = e.getY(); Graphics g = getGraphics(); // get a Graphics for Scrib g.setColor(currentColor); g.drawLine(lastX, lastY, x, y); lastX = x; lastY = y; } // The other method of the MouseMotionListener interface. public void mouseMoved(MouseEvent e) {;} } }