Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Using Components, the GUI Building Blocks

How to Use Buttons

The Button(in the API reference documentation) class provides a default button implementation. A button is a simple control that generates an action event when the user clicks it.

The onscreen appearance of Buttons depends on the platform they're running on and on whether the button is enabled. If you want your program's buttons to look the same for every platform or to otherwise have a special look, you should create a Canvas subclass to implement this look; you can't change the look using a Button subclass. The only facets of a Button's appearance that you can change without creating your own class are the font and text it displays, its foreground and background colors, and (by enabling or disabling the button) whether the button looks enabled or disabled.

Below is an applet that displays three buttons. When you click the left button, it disables the middle button (and itself, since it's no longer useful) and enables the right button. When you click the right button, it enables the middle button and the left button, and disables itself.

Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go to example-1dot1/ButtonDemo.html.

Below is the code that creates the buttons and reacts to button clicks. (Here's the whole program.)

//In initialization code:
    b1 = new Button();
    b1.setLabel("Disable middle button");

    b2 = new Button("Middle button");

    b3 = new Button("Enable middle button");
    . . .

public boolean action(Event e, Object arg) {
    Object target =;
    if (target == b1) { //They clicked "Disable middle button"
        return true;
    if (target == b3) { //They clicked "Enable middle button"
        return true;
    return false;
The above code sample shows how to use all but one of the commonly used Button methods. In addition, Button defines a getLabel() method, which lets you find out what text is displayed on a particular Button.

Previous | Next | Trail Map | Creating a User Interface (AWT Only) | Using Components, the GUI Building Blocks