Java Reference
In-Depth Information
There are several important things to notice about this applet. First, MySwingApplet ex-
tends JApplet . As explained, all Swing-based applets extend JApplet rather than Ap-
plet . Second, the init( ) method initializes the Swing components on the event-dispatching
thread by setting up a call to makeGUI( ) . Notice that this is accomplished through the
use of invokeAndWait( ) rather than invokeLater( ) . Applets must use invokeAndWait(
) because the init( ) method must not return until the entire initialization process has been
completed. In essence, the start( ) method cannot be called until after initialization, which
means that the GUI must be fully constructed.
Inside makeGUI( ) , the two buttons and label are created, and the action listeners are
added to the buttons. Notice that anonymous inner classes are used to implement the action
event handlers. You can use these as a model for implementing other event handlers. One
of the primary advantages is that the object that causes the event is known because it is the
object on which the anonymous inner class is instantiated. Therefore, it is not necessary to
obtain the action command to determine which button generated the event. (Using a lambda
expression would also provide the same advantage.) Finally, the components are added to
the content pane. Although this example is quite simple, this same general approach can be
used when building any Swing GUI that will be used by an applet.
Chapter 16 Self Test
1 . In general, AWT components are heavyweight and Swing components are
____________.
2 . Can the look and feel of a Swing component be changed? If so, what feature enables
this?
3 . What is the most commonly used top-level container for an application?
4 . Top-level containers have several panes. To what pane are components added?
5 . Show how to construct a label that contains the message "Select an entry from the
list".
6 . All interaction with GUI components must take place on what thread?
7 . What is the default action command associated with a JButton ? How can the action
command be changed?
8 . What event is generated when a push button is pressed?
Search WWH ::




Custom Search