The Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton.
All are subclasses of the AbstractButton class, which extends JComponent. Thus, all
buttons share a set of common traits.
AbstractButton contains many methods that allow you to control the behavior of buttons.
For example, you can define different icons that are displayed for the button when it is
disabled, pressed, or selected. Another icon can be used as a rollover icon, which is displayed
when the mouse is positioned over a button. The following methods set these icons:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to be used for the indicated purpose.
The text associated with a button can be read and written via the following methods:
String getText( )
void setText(String str)
Here, str is the text to be associated with the button.
The model used by all buttons is defined by the ButtonModel interface. A button
generates an action event when it is pressed. Other events are possible. Each of the concrete
button classes is examined next.
The JButton class provides the functionality of a push button. You have already seen a
simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be
associated with the push button. Three of its constructors are shown here:
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.
When the button is pressed, an ActionEvent is generated. Using the ActionEvent object
passed to the actionPerformed( ) method of the registered ActionListener, you can obtain
the action command string associated with the button. By default, this is the string displayed
inside the button. However, you can set the action command by calling setActionCommand( )
on the button. You can obtain the action command by calling getActionCommand( ) on the
event object. It is declared like this:
String getActionCommand( )
The action command identifies the button. Thus, when using two or more buttons within
the same application, the action command gives you an easy way to determine which
button was pressed.
Search WWH :