Java Reference
In-Depth Information
the Up button in the ButtonDemo program shown earlier. It requires only an expression
lambda.
Notice how much shorter this code is compared with the original approach. It is also shorter
than it would be if you explicitly used an anonymous inner class.
In general, you can use a lambda expression to handle an event when its listener defines
a functional interface. For example, ItemListener is also a functional interface. Of course,
whether you use the traditional approach, an anonymous inner class, or a lambda expres-
sion will be determined by the precise nature of your application. To gain experience with
each, try converting the event handlers in the foregoing examples to lambda expressions or
anonymous inner classes.
Create a Swing Applet
The preceding example programs have been Swing-based applications. The second type of
program that commonly uses Swing is the applet. Swing-based applets are similar to AWT-
based applets described in Chapter 15 , but with an important difference: A Swing applet
extends JApplet rather than Applet . JApplet is derived from Applet . Thus, JApplet in-
cludes all of the functionality found in Applet and adds support for Swing. JApplet is a
top-level Swing container. Therefore, it includes the various panes described earlier. As a
result, all components are added to JApplet 's content pane in the same way that compon-
ents are added to JFrame 's content pane.
Swing applets use the same four life-cycle methods described in Chapter 15 : init( ) ,
start( ) , stop( ) , and destroy( ) . Of course, you need to override only those methods that
are needed by your applet. In general, painting is accomplished differently in Swing than it
is in the AWT. Thus, a Swing applet will not usually override the paint( ) method.
One other point: All interaction with components in a Swing applet must take place on
the event-dispatching thread, as described in the preceding section. This threading issue ap-
plies to all Swing programs.
Here is an example of a Swing applet. It provides the same functionality as the push-
button example shown earlier in this chapter, but it does so in applet form. It also uses
anonymous inner classes to implement the action event handlers. Figure 16-6 shows the
program when executed by appletviewer .
Search WWH ::




Custom Search