Section 10.4. Applets

   

10.4 Applets

In this section we will look at how to write and use Java applets. Applets are small applications that run on the client. The early success of Java was due in large part to a successful demonstration of an applet running on a client machine via a Web page.

There is some debate at this time regarding the usefulness of applets. They can be cumbersome to download, and the browser wars have made it difficult to deploy mission-critical applets and be sure that your users are able to use them seamlessly.

Rich user interfaces and client applications can now be built using Flash. The most recent version of Flash brings Action Scripting to the forefront, and it features improved database access and XML processing over previous versions. While Flash requires a browser plugin too, and it is arguably not easier to write than an applet is, Flash applications on the client are becoming more popular and useful, especially when integrated with the server-side Flash Gateway for Macromedia JRun or CFMX.

Applets started the excitement surrounding Java, and then moved out of the limelight as Java moved to the server. While servlets have been available for a couple of years , they are tedious to write and are poor choices for pages that need to write out to the browser, for reasons we will see later. JavaServer Pages were introduced in 1999 and quickly garnered a lot of the interest previously reserved for applets. In an interesting twist, there is now a significant trend for moving complex application functionality back onto the client. Programmers will do this with Flash, with applets, and with related Java technology such as Java WebStart, which we will examine in this book. So it is appropriate to look at least briefly at applets.

10.4.1 Applet Basics

Applets are regular Java classes that extend the Applet class. Because of this, you can do just about anything that Java allows you to do from within an applet that runs in its own space on the client. That makes applets arguably the most powerful way to execute programs on the client.

There are a few steps to getting an applet running on a client:

  • Write a Java class that extends the java.applet.Applet class and imports the packages you need.

  • Write an HTML page that calls the applet using the HTML <object> tag.

Using the HTML <object> tag, you specify the size and location of the applet on the page, as well as the class file to be used. The browser then loads the plugin, which contains its own Java Virtual Machine.

In the beginning, you could only view an applet by viewing the Web page in Sun's HotJava browser. This browser is currently in version 3.0 and is still available for free download. However, it is not a full-featured browser, it is slow, and it has little support for the kinds of developments in the language (such as CSS) that users have come to expect.

Applets moved into the big time when they were adopted by Internet Explorer and Netscape browsers. Using a virtual machine embedded in the browser itself, applets could be embedded in an Web page using the HTML <applet> tag. As of HTML 4.0, the W3C has deprecated this tag in favor of <object> , which is more general. Note that older browsers may not recognize the <object> tag. Browser manufacturers have not updated their Java Virtual Machines for a version later than Java 1.1. This poses obvious difficulties to developers interested in deploying applets with functionality defined in later versions of Java.

So Sun devised a plan to propagate the use of applets without being at the mercy of Netscape and Microsoft to keep current. This plan became the Java Plugin. You are likely familiar with this plugin if you have used the < cfform > controls < cftree > , <cfgrid> , and so forth in ColdFusion 5 or later. This 5 MB download allows both Internet Explorer and Netscape to execute applets using this runtime, which should always be up-to-date. Another benefit to the plugin is added user control over the execution environment; see Figure 10.2. The plugin allows users to switch between different versions of Java Virtual Machines, for instance.

Figure 10.2. Sun Java plugin options.

graphics/10fig02.gif

Eventually, Sun determined that limiting the plugin to working with the newer <object> tag was dissuading developers from using applets. As of now, the fate of applets is admittedly up in the air.

Note

You should already have the plugin installed. It comes with the JRE. If for some reason you don't, you need to download it from Sun to execute the examples in this section. If you do have it installed, you can open the plugin outside a browser and review the options it makes available to you. On Windows machines, you access it by double-clicking the icon in the Control Panel.


There are basically two options for writing applets. You can extend java.applet.Applet . You can also choose to write applets using Swing components , which are sophisticated GUI elements located in the javax.swing package. In order to write applets using Swing components, you instead extend javax.swing.JApplet . We will write both versions here.

10.4.2 Viewing Applets

There are two ways to view an applet you write: via a Web page and with the appletviewer utility that ships with the JDK. Let's write a quick applet and view it in the appletviewer , and then in a browser. Note that both ways of viewing an applet require an HTML page.

10.4.3 SimpleApplet.java

 /*  File: SimpleApplet.java  Purpose: print a message */ import java.applet.*; import java.awt.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello, sweetheart!", 50, 25); } 

10.4.4 Using the appletviewer Tool

Compile your source file into a class file in the chp10 directory. We will test the applet using the appletviewer tool that ships with the JDK. Here is a simple file we can use:

10.4.5 ShowSimpleApplet.html

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">  <html> <head> <title>Applet Test</title> </head> <body> <applet align="center"      code="SimpleApplet.class" width="200" height="100"> </applet> </body> </html> 

Now we can call the applet's HTML page using the JDK appletviewer tool, like this:

 C:\>appletviewer  CFusionMX\wwwroot\chp10\ShowSimpleApplet.html 

This is the full path to the file on my Windows XP machine. Note that you need not include the drive. Adjust the command for the location of your HTML file. This should launch the viewer program and display the applet, as shown in Figure 10.3.

Figure 10.3. The appletviewer tool showing the SimpleApplet applet.

graphics/10fig03.gif

10.4.6 Using the Java Plugin and HTML Converter

It can be difficult to use the Java plugin, but it is required if you want to deploy an applet in a live Web page. You need to convert the HTML file that displays the applet so that the browser will invoke the plugin when it is supposed to. It is unrealistic to try to create these tags by hand; it is easier to use Sun's HTML Converter tool.

10.4.7 Advanced Applets

Let's have some fun. Using what we already know about Java, we can go to the API and look through the AWT and Swing packages and find things to put into an applet. While writing applets is not particularly complicated, as you can see, this is a good way to practice what you will need to do when writing real Java programs ”find what's in the API, and determine how to implement and extend its functionality on your own.

Here we'll make an applet that accepts input from the user in the form of a simple freehand drawing program. The applet will use packages that should be available to the greatest number of browsers and not require the plugin.

Here is the code for an applet that allows the user to draw on the screen:

10.4.8 DrawingApplet.java

 /* File: DrawingApplet     Purpose: allows user to draw on an applet    in several different colors. */ import java.applet.*; import java.awt.*; public class DrawingApplet extends Applet { // set color for pen     private Color penColor = Color.black; // name drop down box to choose pen color     private Choice colorPicker; // end x and y coordinates to keep track // of where the mouse is private int endX;     private int endY; // handles things to do when applet starts     public void init () { // set the background color to white         setBackground (Color.white); // Choice creates a drop down box // like an HTML <select>         colorPicker= new Choice(); // add each item to the Choice // like specifying <option> in HTML colorPicker.addItem ("black");         colorPicker.addItem ("blue"); colorPicker.addItem ("green"); colorPicker.addItem ("orange"); colorPicker.addItem ("pink");         colorPicker.addItem ("red");         colorPicker.addItem ("yellow"); // choose the foreground (text) color // and background color of the button         colorPicker.setForeground (Color.black);         colorPicker.setBackground (Color.lightGray); // add the instance         add (new Label ("Pen Color: "));         add (colorPicker);         } // the following two operations are deprecated // but they will work fine, and it is very complicated // to use newer libraries for this, which force you // to implement listener interfaces for everything. // so since we're not going heavily into GUIs... // define what happens on mousedown     public boolean mouseDown (Event e, int x, int y) {   endX = x; endY = y; return true;      } // define what happens on drag   public boolean mouseDrag (Event e, int x, int y) {     Graphics g = getGraphics();     g.setColor (penColor);     g.drawLine (endX, endY, x, y);     endX = x;     endY = y;     return true;   } // here we set the pen color based on the // user choice in colorPicker   public boolean action (Event event, Object arg) {   if (arg.equals ("black"))         penColor = Color.black;   else if (arg.equals ("blue"))         penColor = Color.blue;   else if (arg.equals ("green"))         penColor = Color.green;   else if (arg.equals ("orange"))         penColor = Color.orange;   else if (arg.equals ("pink"))         penColor = Color.pink;   else if (arg.equals ("red"))         penColor = Color.red;   else if (arg.equals ("yellow"))         penColor = Color.yellow;       return true;   } } 

Compile this code and write a quick HTML page like ShowDrawing-Applet.html that displays the applet. Then run it in the appletviewer . You can draw on the applet with your mouse, and use the Choice box to change pen colors. Here I have made what I believe to be a lovely picture of my cat Doodlehead; see Figure 10.4.

Figure 10.4. The DrawingApplet class in action: my cat Doodlehead.

graphics/10fig04.gif

10.4.9 ShowDrawingApplet.html

 <html>  <head> <title>Applet Test</title> </head> <body> Draw something here: <br> <br> <applet align="center"  code="DrawingApplet.class"      width="300" height="300"> </applet> </body> </html> 

   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

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