5.2.2 The Button Class


The following example is an applet that consists of 4 buttons. Three buttons are colored; when you press such a button, the background color of the applet is set to the color of the button chosen. The fourth button resets the background color to the default one, with which you started.

The Applet
The Java Code
import java.applet.Applet;
import java.awt.*;

public class ColorButtons extends Applet {

  Button red, green, blue, reset;
  Color bgColor;

  public void init() {
    //  specify the buttons
    red = new Button();
    red.setBackground(Color.red);
    green = new Button();
    green.setBackground(Color.green);
    blue = new Button();
    blue.setBackground(Color.blue);
    reset = new Button("Reset");
    //  find the default color and choose this for reset button
    bgColor = getBackground();
    reset.setBackground(bgColor);
    //  add the buttons to the applet
    add(red);
    add(green);
    add(blue);
    add(reset);
  }

  public boolean action(Event evt, Object arg) {
    //  if one of the buttons is pressed, change the background color
    if (evt.target == red)        setBackground(Color.red);
    else if (evt.target == green) setBackground(Color.green);
    else if (evt.target == blue)  setBackground(Color.blue);
    else if (evt.target == reset) setBackground(bgColor);
    //  recolor the buttons
    red.setBackground(Color.red);
    green.setBackground(Color.green);
    blue.setBackground(Color.blue);
    reset.setBackground(bgColor);
    // repaint the applet
    repaint();
    return true;
  }
}

This example shows the two ways to construct a button:

The colors of the buttons are set by the setBackground method of the Component class . If you want to change the text that labels an existing button, you can use the setLabel method.

The following table lists the constructors and methods for buttons.

Constructors Meaning
Button() creates a button with no label
Button(String label) creates a button with the given string label
Methods Meaning
getLabel() returns the label of the button
setLabel(String label) changes the label of the button

In this example that effect of pressing a button is handled by the action method. We shall come back to the ways actions and events in applets are handled.

Sometimes buttons must be disabled because the action that it represents is not legal or does not make sense at the moment. An example is the following applet mimicking a stopwatch

In this case, you can call the disable method from the Component class. It will stop the button from responding to events such as mouse clicks and it changes the appearance of the button so that a user knows that it is disabled. Of course, the disable method can be used for other GUI components besides buttons. There also exists an enable method to re-activate a GUI component with respect to events.