|
Button Class
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:
Button();
Button(String label);
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
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.