Previous | Next | Trail Map | Creating a User Interface | 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.

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");
    b3.disable();
    . . .

public boolean action(Event e, Object arg) {
    Object target = e.target;
         
    if (target == b1) { //They clicked "Disable middle button"
        b2.disable();
        b1.disable();
        b3.enable();
        return true;
    }
    if (target == b3) { //They clicked "Enable middle button"
        b2.enable();
        b1.enable();
        b3.disable();
        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 | Using Components, the GUI Building Blocks