Questions and Exercises

Swing Based Applets

Now that we've covered how to create applets based on the 1.1 version of the Java Platform, this section gives an overview of how to run and write Swing-based applets.

Running Swing-Based Applets

This section explains how to run applets that use Swing components. For information on writing Swing applets, see the section Writing Swing-Based Applets (page 458).

You can run Swing applets in any browser that has the appropriate version of Java Plug-in installed. [1] You can do this by visiting the URL for either of the preceding applets. Another alternative is to use Applet Viewer (appletviewer). [2] Java Plug-in supports certain versions of Netscape Navigator and Internet Explorer. See the Java Plug-in documentation on this book's CD for details.

[1] The Java Plug-in is included in the JRE (as of version 1.2 of the Java 2 platform).

[2] We recommend that you use Applet Viewer in version 1.2 (and higher) of the Java 2 platform. If you're using JDK 1.1 Applet Viewer, you'll need to load the Swing JAR file.

To test whether your browser can run Swing applets, go to this page in the online tutorial:

http://java.sun.com/docs/books/tutorial/uiswing/start/HelloSwingApplet.html

You should see a box that looks like this. [1]

[1] HelloSwingApplet.java and HelloSwingApplet.html are included on the CD and are available online. See Code Samples (page 463).

Figure 121. A snapshot of the simple applet, HelloSwingApplet.

graphics/apbfig20.gif

If you view the source of that Web page, you'll see that the HTML code for including the applet is rather convoluted. The good news is that you can generate the HTML code automatically from a simple tag. See the Java Plug-in documentation for details on downloading a free HTML converter. [2]

[2] The Java Plug-in documentation is online at http://java.sun.com/products/plugin/index.html

Writing Swing-Based Applets

This section covers the JApplet class, which enables applets to use Swing components. JApplet is a subclass of java.applet.Applet. If you've never written a regular applet before, we urge you to read the preceding sections in this appendix before proceeding with this section.

Any applet that contains Swing components must be implemented with a subclass of JApplet. [3] Here's a Swing version of one of the applets that helped make Java famousan applet that animates our mascot, Duke, doing cartwheels.

[3] API documentation for this class is available on this book's CD and online at http://java.sun.com/j2se/1.3/docs/api/javax/swing/JApplet.html

Figure 122. One frame of the Duke tumbling applet.

graphics/apbfig21.gif

The CD that accompanies this book includes the source code (TumbleItem.java and SwingWorker.java) and the 17 images used in this applet. [1]

[1] The directory with the tumbling Duke images on the CD is: JavaTutorial/uiswing/components/example-swing/images/tumble/

JApplet Features

JApplet adds two major features to the functionality that it inherits from java.applet.Applet. First, JApplet provides support for assistive technologies. Second, because JApplet is a top-level Swing container, each Swing applet has a root pane. The most noticeable results of the root pane's presence are support for adding a menu bar and the need to use a content pane.

As described in Overview of the Swing API (page 352) in Chapter 10, each top-level container, such as JApplet, has a single content pane. The content pane makes Swing applets different from regular applets in the following ways:

  • You add components to a Swing applet's content pane, not directly to the applet.
  • You set the layout manager on a Swing applet's content pane, not directly on the applet.
  • The default layout manager for a Swing applet's content pane is BorderLayout. This differs from the default layout manager for Applet, which is FlowLayout.
  • You should not put painting code directly in a JApplet object. See the section Converting AWT Applets to Swing Applets (page 462) for information on converting applet painting code.

JDK 1.1 Note

If you run a Swing applet using JDK 1.1 and JFC 1.1, you might see an error message that looks like this:

Swing: checked access to system event queue. 

You can often avoid this message by telling the applet not to check whether it has access to the system event queue. To do so, put the following code in the constructor for the applet class:

getRootPane().putClientProperty("defeatSystemEventQueueCheck", 
 Boolean.TRUE); 

 

Threads in Swing Applets

Because applets inherently use multiple threads and Swing components aren't thread safe, you should take care with threads in Swing applets. It's generally considered safe to create and to manipulate Swing components directly in the init method. However, the other milestone methodsstart, stop, and destroymight cause trouble when the browser invokes them after the applet's already visible. To avoid trouble, you should make these methods thread safe.

For example, when you implement a stop or a start method, be aware that the browser doesn't call them from the event-dispatching thread. Thus, those methods shouldn't affect or query Swing components directly. Instead, they should use such techniques as using the SwingUtilities.invokeLater method to affect components.

For more information about using threads, see the section Threads and Swing (page 378) in Chapter 10 and Chapter 8, Threads: Doing Two or More Tasks at Once (page 269). Threads in AWT applets was covered in an earlier section, Threads in AWT Applets (page 449).

Using Images in a Swing Applet

Recall that the Applet class provides the getImage method for loading images into an applet. The getImage method creates and returns an Image object that represents the loaded image. Because Swing components use Icons rather than Images to refer to pictures, Swing applets tend not to use getImage. Instead, Swing applets usually create instances of ImageIconan icon loaded from an image file. ImageIcon comes with a code-saving benefit: It handles image tracking automatically.

The animation of Duke doing cartwheels requires 17 pictures, with one ImageIcon per picture. Because images can take a long time to load, the icons are loaded in a separate thread implemented by a SwingWorker object. The applet's init method starts the thread by creating the SwingWorker object. Here's the code:

public void init() { 
 ... 
 imgs = new ImageIcon[nimgs]; 
 final SwingWorker worker = new SwingWorker() { 
 public Object construct() { 
 URL baseURL = getCodeBase(); 
 String prefix = dir + "/T"; 
 //Images are numbered 1 to nimgs, 
 //but fill array from 0 to nimgs-1 
 for (int i = 0; i < nimgs; i++) { 
 imgs[i] = new ImageIcon(getURL(baseURL, prefix 
 + (i+1) + ".gif")); 
 } 
 finishLoading = true; 
 return imgs; 
 } ... 
 }; 
 worker.start(); 
} 

To create an ImageIcon and load it with an image, you specify the image file's URL to the ImageIcon's constructor. The preceding applet defines a method named getURL to construct the URL for each image file. Here is the code:

protected URL getURL(URL codeBase, String filename) { 
 URL url = null; 
 try { 
 url = new URL(codeBase, filename); 
 } catch (java.net.MalformedURLException e) { 
 System.out.println("Couldn't create image: " + 
 "badly specified URL"); 
 return null; 
 } 
 return url; 
} 

Providing an OBJECT/EMBED Tag for Java Plug-in

To run, an applet must be included in an HTML page. If you're using Applet Viewer to run a Swing applet, you include the applet by using an tag. [1] Here's the tag for the cartwheeling Duke applet:

[1] To find out about the various tag parameters, refer to the section Using theTag (page 438).

 
Your browser is completely ignoring the <APPLET> tag! 

To make an applet work with the Java Plug-in, you need to convert the tag into and tags so that an applet can be included in an HTML page. You can download a free tool that automatically generates the necessary tags from an tag. To download Java Plug-in and the HTML conversion tool, as well as related documentation, go to the Java Plug-in home page. [2]

[2] http://java.sun.com/products/plugin/index.html

Because the Java Plug-in can take a while to download and load into the browser, it's considerate to give users advance warning that a page contains an applet. You might have noticed that the tutorial's applets don't run the same page as the text that describes the applet. Instead we provide a screenshot of the applet running and a link that brings up a separate browser window in which to run the applet. We feel that this provides a better experience because users can choose whether to visit a page that contains an applet.

Converting AWT Applets to Swing Applets

This section gives you several tips for converting your AWT applets to Swing applets. First, remember that AWT programs add components directly to the Applet object and directly set the applet's layout manager. Swing applets, on the other hand, add components to and set the layout manager on the JApplet's content pane. So to convert an applet, you must make the source code changes described in that section. Furthermore, whereas FlowLayout is the default layout manager for AWT applets, BorderLayout is the default layout manager for Swing applets. This has two repercussions:

  • If you want to use a FlowLayout, the Swing version of your program must use setLayout on the content pane to specify it.
  • If you specified BorderLayout in your AWT applet, you can remove the setLayout statement from the Swing version.

Don't paint directly in a JApplet, because it will be covered by the applet's content pane. Instead of seeing your painting, you'll just see a blank area. The solution is to have a custom component do the painting, and add it to the content pane. See the instructions for converting canvases for tips on choosing a class for the custom component and for moving the paint code to the appropriate method.

Be very aware of thread issues when converting your applet. Because the stop and start methods aren't called from the event-dispatching thread, you should use SwingUtilities.invokeLater in those methods whenever you make a change that might result in a call upon a component. See Threads and Swing (page 378) in Chapter 10 for more information.

Lastly, your applet's users will probably use Java Plug-in to run your applet. So you will need to convert the tag to an OBJECT/EMBED tag. An automatic HTML converter can be found at the Java Plug-in site.

For More Information

A number of resources on the Web teach the basics of HTML. A quick search on your favorite search engine will yield numerous HTML tutorials. The World Wide Web Consortium (W3C) hosts an excellent and compact tutorial, "Getting Started with HTML":

http://www.w3.org/MarkUp/Guide/

For more complete information on Swing, see The JFC Swing Tutorial book or the online tutorial:

http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html

Code Samples

Getting Started

Object-Oriented Programming Concepts

Language Basics

Object Basics and Simple Data Objects

Classes and Inheritance

Interfaces and Packages

Handling Errors Using Exceptions

Threads: Doing Two or More Tasks at Once

I/O: Reading and Writing

User Interfaces That Swing

Appendix A. Common Problems and Their Solutions

Appendix B. Internet-Ready Applets

Appendix C. Collections

Appendix D. Deprecated Thread Methods

Appendix E. Reference



The Java Tutorial(c) A Short Course on the Basics
The Java Tutorial: A Short Course on the Basics, 4th Edition
ISBN: 0321334205
EAN: 2147483647
Year: 2002
Pages: 125

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net