Let's look at the code, which can be found in ButtonBox.java:

Class ButtonBox extends our DrawBox class and inherits the public methods: mouseDown, mouseUp, and mouseDrag. It also inherits the variables: currentX, currentY, startX, startY, and dragMode. The ButtonBox class itself adds two new variables: choice and color. The choice variable specifies the choice menu that will be added to the applet, and the color variable specifies the color in which the applet will draw its next rectangle:

public class ButtonBox extends DrawBox {
        Choice choice;
        Color color;

Initializing the Applet

Before we do anything, we need to add the choice menu in the initialization phase. We create a choice menu with the new function, and add items to it with the addItem function. The Choice class and the Color class are part of the java.awt package. We initialize the color to be the default color, i.e. the color of the current foreground (black). Then we add the choice menu to the applet:
        public void init() {
              choice = new Choice ();

              choice.addItem ("Default");
              choice.addItem ("Red");
              choice.addItem ("Yellow");
              choice.addItem ("Blue");

              color = getForeground();
              add (choice);
        }

Painting

We need to overload the paint function. Since we need to change its behavior, we cannot use the DrawBox's version of it. There is only one line that we need to add to the paint function, and that is to set the color of the graphics context to be equal to color:
              g.setColor(color);

Event Handling: User Interaction

When the user selects a new color from the choice menu, the action function gets called, because it generates an event. In the action function we first check to see if the target of the event is the choice menu (it could also be a button or something else if we had them in our applet). If it is the choice menu, then we cast the arg parameter into a String, since we have stored strings in our choice menu. Next, we compare the string name with tha names of the different entries in the choice menu. If we have a hit, we set the color variable to be the selected color:
        public boolean action(Event event, Object arg) {

                if (event.target == choice) {
                        String str = (String)arg;
                        if (str.equals("Default"))
                                color = getForeground();
                        else if (str.equals("Red"))
                                color = Color.red;
                        else if (str.equals("Yellow"))
                                color = Color.yellow;
                        else color = Color.blue;

                }
                return true;


Back to Lecture3