Java Reference
In-Depth Information
will normally want to use invokeLater( ) , as the preceding program does. However, when
constructing the initial GUI for an applet, you will want to use invokeAndWait( ) . (Creat-
ing Swing applets is described later in this chapter.)
One more point: The preceding program does not respond to any events, because JLabel
is a passive component. In other words, a JLabel does not generate any events. Therefore,
the preceding program does not include any event handlers. However, all other components
generate events to which your program must respond, as the subsequent examples in this
chapter show.
Use JButton
One of the most commonly used Swing controls is the push button. A push button is an
instance of JButton . JButton inherits the abstract class AbstractButton , which defines
the functionality common to all buttons. Swing push buttons can contain text, an image, or
both, but this topic uses only text-based buttons.
JButton supplies several constructors. The one used here is
JButton(String msg )
Here, msg specifies the string that will be displayed inside the button.
When a push button is pressed, it generates an ActionEvent . ActionEvent is defined
by the AWT and also used by Swing. JButton provides the following methods, which are
used to add or remove an action listener:
void addActionListener(ActionListener al )
void removeActionListener(ActionListener al )
Here, al specifies an object that will receive event notifications. This object must be an in-
stance of a class that implements the ActionListener interface.
The ActionListener interface defines only one method: actionPerformed( ) . It is shown
here:
void actionPerformed(ActionEvent ae )
This method is called when a button is pressed. In other words, it is the event handler that is
called when a button press event has occurred. Your implementation of actionPerformed(
) must quickly respond to that event and return. As a general rule, event handlers must
not engage in long operations, because doing so will slow down the entire application. If a
Search WWH ::




Custom Search