Java Reference
In-Depth Information
Swing Buttons
The javax.swing.JButton class has several constructors, including:
public JButton(String label). Creates a JButton with the given label.
public JButton(Icon icon). Creates a JButton with the specified icon.
Swing buttons can have an icon displayed on the button.
public JButton(String label, Icon icon).
Creates a JButton with both text
and an icon.
The methods in the JButton class related to events include:
public void addActionListener(ActionListener a). Registers the given
listener with the button to receive the ActionEvent generated when the
button is clicked.
public void addChangeListener(ChangeListener c). Registers the given
listener to receive the ChangeEvent generated when the state of the but-
ton changes.
public void setActionCommand(String c).
Sets the action command for
the button.
public void doClick().
Programmatically clicks the button, just as if the
user had done it.
public void setMnemonic(int mnemonic). Assigns a virtual key to the
button so that it can be clicked using the keyboard. The argument
passed in is one of the static fields in the KeyEvent class. For example,
if the mnemonic is set to be VK_B, pressing Alt+B when the button has
focus will cause the button to be clicked.
public void setPressedIcon(Icon icon).
Assigns an icon that is displayed
when the button is clicked.
The JButton class has dozens more methods, so check the documentation to
find out other features of JButton. You will notice with buttons (and all the
other components) that the Swing version of the component has many more
methods and features than its AWT counterpart. For example, the doClick()
and setMnemonic() methods are not in the java.awt.Button class.
The following ButtonDemo program instantiates three JButton components
and adds them to a JFrame. The ColorChanger class (defined immediately
after the ButtonDemo class) provides the event handling for the three buttons.
Study the two classes and try to determine what the program does.
Search WWH ::




Custom Search