img
Next, event listeners for the button's action events are added by the code shown here:
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});
Here, anonymous inner classes are used to provide the event handlers for the two buttons.
Each time a button is pressed, the string displayed in jlab is changed to reflect which button
was pressed.
Next, the buttons are added to the content pane of jfrm:
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
Finally, jlab is added to the content pane and window is made visible. When you run the
program, each time you press a button, a message is displayed in the label that indicates
which button was pressed.
One last point: Remember that all event handlers, such as actionPerformed( ), are called
on the event dispatching thread. Therefore, an event handler must return quickly in order to
avoid slowing down the application. If your application needs to do something time
consuming as the result of an event, it must use a separate thread.
Create a Swing Applet
The second type of program that commonly uses Swing is the applet. Swing-based applets
are similar to AWT-based applets, but with an important difference: A Swing applet extends
JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of
the functionality found in Applet and adds support for Swing. JApplet is a top-level Swing
container, which means that it is not derived from JComponent. Because JApplet is a
top-level container, it includes the various panes described earlier. This means that all
components are added to JApplet's content pane in the same way that components are
added to JFrame's content pane.
Swing applets use the same four lifecycle methods as described in Chapter 21: init( ),
start( ), stop( ), and destroy( ). Of course, you need override only those methods that are
needed by your applet. Painting is accomplished differently in Swing than it is in the AWT,
and a Swing applet will not normally override the paint( ) method. (Painting in Swing is
described later in this chapter.)
One other point: All interaction with components in a Swing applet must take place on
the event dispatching thread, as described in the previous section. This threading issue
applies to all Swing programs.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home