Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages


How to Use Buttons

To create a button, you can instantiate one of the many subclasses of the AbstractButton(in the API reference documentation) class. This section explains the basic button API that AbstractButton defines -- and thus all Swing buttons have in common. Because the JButton subclass of AbstractButton defines no new public API, this page uses it to show how buttons work. The following table shows all the Swing-defined AbstractButton subclasses that you might want to instantiate:

ClassSummaryWhere Described
JButton(in the API reference documentation) A common button. This section.
JCheckBox(in the API reference documentation) A typical check box. How to Use Check Boxes
JRadioButton(in the API reference documentation) One of a group of radio buttons. How to Use Radio Buttons
JMenuItem(in the API reference documentation) An item in a menu. [nowhere yet]
JMenu(in the API reference documentation) A menu. [nowhere yet]

Here is a picture of an application that displays three buttons:


Try this:
  1. Compile and run the application. The source file is ButtonDemo.java.
    See Getting Started with Swing if you need help.
  2. Click the left button.
    It disables the middle button (and itself, since it's no longer useful) and enables the right button.
  3. Click the right button.
    It enables the middle button and the left button, and disables itself.

As the ButtonDemo example shows, a Swing button can display both text and an image. In ButtonDemo, each button has its text in a different place, relative to its image. The underlined letter in each button's text shows the keyboard alternative for each button.

When a button is disabled, the look-and-feel automatically generates the button's disabled appearance. However, you could provide an image to be substituted for the normal image. For example, you could provide gray versions of the images used in the left and right buttons.

How you implement event handling depends on the type of button you use and how you use it. All Swing buttons can generate action, change, and item events, as well as the usual low-level events. The ButtonDemo example implements just an action listener.

Below is the code from ButtonDemo.java that creates the buttons in the previous example and reacts to button clicks. The bold code is the code that would remain if the buttons had no images.

//In initialization code:
    ImageIcon leftButtonIcon = new ImageIcon("right.gif");
    ImageIcon middleButtonIcon = new ImageIcon("middle.gif");
    ImageIcon rightButtonIcon = new ImageIcon("left.gif");

    b1 = new JButton("Disable middle button", leftButtonIcon);
    b1.setVerticalTextPosition(AbstractButton.CENTER);
    b1.setHorizontalTextPosition(AbstractButton.LEFT);
    b1.setKeyAccelerator('d');
    b1.setActionCommand("disable");

    b2 = new JButton("Middle button", middleButtonIcon);
    b2.setVerticalTextPosition(AbstractButton.BOTTOM);
    b2.setHorizontalTextPosition(AbstractButton.CENTER);
    b2.setKeyAccelerator('m');

    b3 = new JButton("Enable middle button", rightButtonIcon);
    //Use the default text position of CENTER, RIGHT.
    b3.setKeyAccelerator('e');
    b3.setActionCommand("enable");
    b3.setEnabled(false);

    //Listen for actions on buttons 1 and 3.
    b1.addActionListener(this);
    b3.addActionListener(this);
    . . .
}

public void actionPerformed(java.awt.event.ActionEvent e) {
    if (e.getActionCommand().equals("disable")) {
        b2.setEnabled(false);
        b1.setEnabled(false);
        b3.setEnabled(true);
    } else { 
        b2.setEnabled(true);
        b1.setEnabled(true);
        b3.setEnabled(false);
    }
}
The following tables list the commonly used AbstractButton methods and JButton constructors. You can see most of this API in action by playing with the Buttons pane in the SwingSet example that's part of the Swing release.. See the release's top-level README.txt for help finding and using SwingSet.

The API for using buttons falls into three categories:

Setting or Getting the Button's Contents
Method or Constructor Purpose Example
JButton(String, Icon)
JButton(String)
JButton(Icon)
JButton()
Create a JButton instance, initializing it to have the specified text/image. ButtonDemo.java
void setText(String)
String getText()
Set or get the text displayed by the button. [none yet]
void setIcon(Icon)
Icon getIcon()
Set or get the image displayed by the button when the button isn't selected or pressed. [none yet]
void setDisabledIcon(Icon)
Icon getDisabledIcon()
Set or get the image displayed by the button when it's disabled. If you don't specify a disabled image, then the look-and-feel creates one by manipulating the default image. [none yet]
void setPressedIcon(Icon)
Icon getPressedIcon()
Set or get the image displayed by the button when it's being pressed. [none yet]
void setSelectedIcon(Icon)
Icon getSelectedIcon()
Set or get the image displayed by the button when it's selected. [none yet]
void setDisabledSelectedIcon(Icon)
Icon getDisabledSelectedIcon()
Set or get the image displayed by the button when it's both disabled and selected (at the same time). If you don't specify a disabled selected image, then the look-and-feel creates one by manipulating the selected [check] image. [none yet]
void setRolloverIcon(Icon)
Icon getRolloverIcon()
Set or get the image displayed by the button when the cursor passes over the unpressed button. [none yet]

Fine Tuning the Button's Appearance
Method or Constructor Purpose Example
void setHorizontalAlignment(int)
void setVerticalAlignment(int)
int getHorizontalAlignment()
int getVerticalAlignment()
Set or get where in the button its contents should be placed. The AbstractButton class defines three possible values for horizontal alignment: LEFT, CENTER (the default), and RIGHT. For vertical alignment: TOP, CENTER (the default), and BOTTOM. [none yet]
void setHorizontalTextPosition(int)
void setVerticalTextPosition(int)
int getHorizontalTextPosition()
int getVerticalTextPosition()
Set or get where the button's text should be placed, relative to the button's image. The AbstractButton class defines three possible values for horizontal position: LEFT, CENTER, and RIGHT (the default). For vertical position: TOP, CENTER (the default), and BOTTOM. [none yet]
void setMargin(Insets)
Insets getMargin()
Set or get the number of pixels between the button's border and its contents. [none yet]
void setFocusPainted(boolean)
boolean isFocusPainted()
Set or get whether the button should look different when it has the focus. [none yet]
void setBorderPainted(boolean)
boolean isBorderPainted()
Set or get whether the border of the button should be painted. [none yet]

Implementing the Button's Functionality
Method or Constructor Purpose Example
void setSelected(boolean)
boolean isSelected()
Set or get whether the button is selected. Makes sense only for buttons that have on/off state, such as check boxes. [none yet]
Object[] getSelectedObjects() Get the objects selected within the button. Makes sense only for buttons such as Menus that contain multiple selectable items. [CHECK! I don't see this used anywhere.] [none yet]
void setActionCommand(String)
String getActionCommand(void)
Set or get the name of the action performed by the button. [none yet]
void setKeyAccelerator(char)
char getKeyAccelerator()
Set or get the keyboard alternative to clicking the button. ButtonDemo.java
void addActionListener(ActionListener)
ActionListener removeActionListener()
Add or remove an object that listens for action events fired by the button. [none yet]
void addChangeListener(ChangeListener)
ChangeListener removeChangeListener()
Add or remove an object that listens for change events fired by the button. [none yet]
void addItemListener(ItemListener)
ItemListener removeItemListener()
Add or remove an object that listens for item events fired by the button. [none yet]
void doClick() Programmatically perform a "click". [none yet]


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages