Applets Core Java

Applets are Java programs that are included in an HTML page. The HTML page must tell the browser which applets to load and then where to put each applet on the web page. As you might expect, the tag needed to use an applet must tell the browser where to get the class files, and how the applet is positioned on the web page (size, location, and so on). The browser then retrieves the class files from the Internet (or from a directory on the user’s machine) and automatically runs the applet.

When applets were first developed, you had to use Sun’s HotJava browser to view web pages that contained applets. Naturally, few users were willing to use a separate browser just to enjoy a new web feature. Java applets became really popular when Netscape included a Java virtual machine in its Navigator browser. Microsoft Internet Explorer soon followed suit. Unfortunately, two problems happened.

Netscape didn’t keep up with more modern versions of Java, and Microsoft vacillated between reluctantly supporting outdated Java versions and dropping Java support altogether.

To overcome this problem, Sun released a tool called the “Java Plug-in.” Using the various extension mechanisms, it seamlessly plugs in to a variety of browsers and enables them to execute Java applets by using an external Java runtime environment that Sun supplies. By keeping the Plug -in up -to -date, you can always take advantage of the latest and greatest features of Java.

NOTE: To run the applets in this chapter in a browser, you need to install the current version of the Java Plug-in and make sure your browser is connected with the Plug-in.

A Simple Applet

For tradition’s sake, let’s write a NotHelloWorldprogram as an applet. An applet is simply a Java class that extends the java.applet.Appletclass. In this book, we will use Swing to implement applets. All of our applets will extend the JAppletclass, the superclass for Swing applets. JAppletis an immediate subclass of the ordinary Applet class.

Applet inheritance diagram

Applet inheritance diagram

NOTE: If your applet contains Swing components, you must extend the JApplet class. Swing components inside a plain Applet don’t paint correctly.

Listing below shows the code for an applet version of “Not Hello World”. However, because the applet lives inside a web page, there is no need to specify a method for exiting the applet.

NotHelloWorldApplet.java

To execute the applet, you carry out two steps:

  1. Compile your Java source files into class files.
  2. Create an HTML file that tells the browser which class file to load first and how to size the applet.

It is customary (but not necessary) to give the HTML file the same name as that of the applet class inside. So, following this tradition, we call the file Not Hello World Applet .html. Here are the contents of the file:

Before you view the applet in a browser, it is a good idea to test it in the applet viewer program that is a part of the JDK. To use the applet viewer in our example, enter applet viewer Not Hello World Applet .htmlat the command line. The command -line argument for the applet viewer program is thename of the HTML file, not the class file. the applet viewer displayingthis applet.

Viewing an applet in the applet viewer

Viewing an applet in the applet viewer

TIP: Here is a weird trick to avoid the additional HTML file. Add an applet tag as a comment inside the source file:

Then run the applet viewer with the source file as its command-line argument:

We aren’t recommending this as standard practice, but it can come in handy if you want to minimize the number of files that you need to worry about during testing.

TIP: You can also run applets from inside your integrated environment. In Eclipse, you select Run -> Run as -> Java Applet from the menu. The applet viewer is good for the first stage of testing, but at some point you need torun your applets in a browser to see them in the same way a user might use them. Inparticular, the applet viewer program shows you only the applet, not the surrounding HTML text. If an HTML file contains multiple applet tags, the applet viewer popsup multiple windows.

To properly view the applet, simply load the HTML file into the browser. If the applet doesn’t show up, you need to install the Java Plug-in.

Viewing an applet in a browser

Viewing an applet in a browser

TIP: If you make a change to your applet and recompile, you need to restart the browser sothat it loads the new class files. Simply refreshing the HTML page will not load the new code. This is a hassle when you are debugging an applet. You can avoid the painful browser restart from the Java console. Launch the console and issue the x command, which clears the classloader cache. Then you can reload the HTML page, and the new applet code is used. Under Windows, open the Java Plug-in control in the Windows control panel. Under Linux, run jcontroland request that the Java console be displayed. The console will pop up whenever an applet is loaded.

Converting Applications to Applets

It is easy to convert a graphical Java application into an applet that you can embed in a web page. Essentially, all of the user interface code can stay the same. Here are the specific steps:

  1. Make an HTML page with the appropriate tag to load the applet code.
  2. Supply a subclass of the JAppletclass. Make this class public. Otherwise, the applet cannot be loaded.
  3. Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be displayed inside the browser.
  4. Move any initialization code from the frame window constructor to the initmethod of the applet. You don’t need to explicitly construct the applet object —the browser instantiates it for you and calls the initmethod.
  5. Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.
  6. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.
  7. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. (You can, of course, title the web page itself, using the HTML title tag.)
  8. Don’t call setVisible(true). The applet is displayed automatically.

java.applet.Applet1.0

  • void init()
    is called when the applet is first loaded. Override this method and place all initialization code here.21
  • void start()
    override this method for code that needs to be executed every time the user visits the browser page containing this applet. A typical action is to reactivate a thread.
  • void stop()
    override this method for code that needs to be executed every time the user leaves the browser page containing this applet. A typical action is to deactivate a thread.
  • void destroy()
    override this method for code that needs to be executed when the user exits the browser.
  • void resize(int width, int height)
    requests that the applet be resized. This would be a great method if it worked on web pages; unfortunately, it does not work in current browsers because it interferes with their page-layout mechanisms.

The Applet HTML Tag and Its Attributes

In its most basic form, an example for using the applet tag looks like this:

As you have seen, the code attribute gives the name of the class file and must include the .class extension; the width and height attributes size the window that will hold the applet. Both are measured in pixels. You also need a matching </applet>tag that marks the end of the HTML tagging needed for an applet. The text between the <applet>and </applet> tags is displayed only if the browser cannot show applets. The code, width, and height attributes are required. If any are missing, the browser cannot load your applet.

All this information would usually be embedded in an HTML page that, at the very least, might look like this:

You can use the following attributes within the applet tag:

  • width, height
    These attributes are required and give the width and height of the applet, measured in pixels. In the applet viewer, this is the initial size of the applet. You can resize any window that the applet viewer creates. In a browser, you cannot resize the applet.
  • You will need to make a good guess about how much space your applet requires to show up well for all users.
  • align
    This attribute specifies the alignment of the applet. The attribute values are the same as for the align attribute of the HTML imgtag.
  • vspace, hspace
    These optional attributes specify the number of pixels above and below the applet (vspace) and on each side of the applet ( hspace).
  • code
    This attribute gives the name of the applet’s class file. This name is taken relative to the codebase or relative to the current page if the codebase is not specified.

The path name must match the package of the applet class. For example, if the applet class is in the package com .my company, then the attribute is code="com /mycompany /MyApplet .class".

The alternative code="com.mycompany.MyApplet.class" is also permitted. But you cannot useabsolute path names here. Use the codebase attribute if your class file is located elsewhere.

The code attribute specifies only the name of the class that contains the applet class. Of course, your applet may contain other class files. Once the browser’s class loader loads the class containing the applet, it will realize that it needs more class files and will load them. Either the code or the object attribute is required.

  • codebase
    This optional attribute is a URL for locating the class files. You can use an absolute URL, even to a different server. Most commonly, though, this is a relative URL that points to a subdirectory. For example, if the file layout looks like this:

then you use the following tag in MyPage.html:

  • archive
    This optional attribute lists the JAR file or files containing classes and other resources for the applet. These files are fetched from the web server before the applet is loaded. This technique speeds up the loading process significantly because only one HTTP request is necessary to load a JAR file that contains many smaller files. The JAR files are separated by commas. For example:
  • object
    This tag lets you specify the name of a file that contains the serialized applet object.

(An object is serialized when you write all its instance fields to a file.) To display the applet, the object is deserializedfrom the file to return it to its previous state. When you use this attribute, the initmethod is not called, but the applet’s start method is called. Before serializing an applet object, you should call its stop method. This feature is useful for implementing a persistent browser that automatically reloads its applets and has them return to the same state that they were in when the browser was closed. This is a specialized feature, not normally encountered by web page designers.

Either code or object must be present in every applet tag. For example:

  • name
    Scripters will want to give the applet a name attribute that they can use to refer to the applet when scripting. Both Netscape and Internet Explorer let you call methods of an applet on a page through JavaScript. This is not a book on JavaScript, so we only give you a brief idea of the code that is required to call Java code from JavaScript.

NOTE: JavaScript is a scripting language that can be used inside web pages, invented by Netscape and originally called LiveScript. It has little to do with Java, except for some similarity in syntax. It was a marketing move to call it JavaScript. A subset (with the catchy name of ECMAScript) is standardized as ECMA-262. But, to nobody’s surprise, Netscape and Microsoft support incompatible extensions of that standard in their browsers.

To access an applet from JavaScript, you first have to give it a name.

You can then refer to the object as document.applets.appletname. For example:

Through the magic of the integration between Java and JavaScript that both Netscape and Internet Explorer provide, you can call applet methods:

The name attribute is also essential when you want two applets on the same page to communicate with each other directly. You specify a name for each current applet instance. You pass this string to the get Applet method of the Applet Context class. We discuss this mechanism, called inter -applet communication, later.

NOTE: In Francis Lu uses Java Script-to- Java communication to solve an age-old problem: to resize an applet so that it isn’t bound by hardcoded width and height attributes. This is a good example of the integration between Java and JavaScript.

  • alt
    Java may be deactivated in the browser, perhaps by a paranoid system administrator.

You can then use the alt attribute to display a message to these unfortunate souls.

If a browser cannot process applets at all, it ignores the unknown applet and paramtags. All text between the <applet>and </applet>tags is displayed by the browser.

Conversely, Java-aware browsers do not display any text between the <applet>and </applet>tags. You can display messages inside these tags for those poor folks that use a prehistoric browser. For example:

If your browser could show Java, you would see my applet here.

The object Tag

The object tag is part of the HTML 4.0 standard, and the W3 consortium suggests that people use it instead of the applet tag. There are 35 different attributes to the object tag, most of which (such as onkeydown) are relevant only to people writing Dynamic HTML. The various positioning attributes such as align and height work exactly as they did for the applet tag.

The key attribute in the object tag for your Java applets is the classid attribute. This attribute specifies the location of the object. Of course, object tags can load different kinds of objects, such as Java applets or ActiveX components like the Java Plug -in itself. In the codetypeattribute, you specify the nature of the object. For example, Java applets have a code type of application/java. Here is an object tag to load a Java applet:

Note that the classid attribute can be followed by a codebase attribute that works exactly as it did with the applet tag.

Use of Parameters to Pass Information to Applets

Just as applications can use command -line information, applets can use parameters that are embedded in the HTML file. This is done by the HTML tag called paramalong with attributes that you define. For example, suppose you want to let the web page determine the style of the font to use in your applet. You could use the following HTML tags:

You then pick up the value of the parameter, using the getParametermethod of the Applet class, as in the following example:

NOTE: You can call the getParametermethod only in the initmethod of the applet, not in the constructor. When the applet constructor is executed, the parameters are not yet prepared.

Because the layout of most nontrivial applets is determined by parameters, we recommend that you don’t supply constructors to applets. Simply place all initialization code into the initmethod.

Parameters are always returned as strings. You need to convert the string to a numeric type if that is what is called for. You do this in the standard way by using the appropriate method, such as parseIntof the Integer class.

For example, if we wanted to add a size parameter for the font, then the HTML code might look like this:

The following source code shows how to read the integer parameter:

NOTE: A case-insensitive comparison is used when matching the name attribute value in the paramtag and the argument of the get Parameter method.

In addition to ensuring that the parameters match in your code, you should find out whether or not the size parameter was left out. You do this with a simple test for null.

Here is a useful applet that uses parameters extensively. The applet draws a bar chart.

A chart applet

A chart applet

This applet takes the labels and the heights of the bars from the paramvalues in the HTML file. Here is what the HTML file:

You could have set up an array of strings and an array of numbers in the applet, but there are two advantages to using the parameter mechanism instead. You can have multiple copies of the same applet on your web page, showing different graphs: just put two applet tags with different sets of parameters on the page. And you can change the data that you want to chart. Admittedly, the diameters of the planets will stay the same for quite some time, but suppose your web page contains a chart of weekly sales data. It is easy to update the web page because it is plain text. Editing and recompiling a Java file weekly is more tedious.

In fact, there are commercial JavaBeans components (beans) that make much fancier graphs than the one in our chart applet. If you buy one, you can drop it into your web page and feed it parameters without ever needing to know how the applet renders thegraphs.

java.applet.Applet

  • public String getParameter(String name)
    gets the value of a parameter defined with a paramtag in the web page loading the applet. The string name is case sensitive.
  • public String getAppletInfo()
    is a method that many applet authors override to return a string that contains information about the author, version, and copyright of the current applet. You need to create this information by overriding this method in your applet class.
  • public String[][] getParameterInfo()
    is a method that you can override to return an array of paramtag options that this applet supports. Each row contains three entries: the name, the type, and a description of the parameter. Here is an example:

Accessing Image and Audio Files

Applets can handle both images and audio. As we write this, images must be in GIF, PNG, or JPEG form, audio files in AU, AIFF, WAV, or MIDI. Animated GIFs are supported, and the animation is displayed.

You specify the locations of image and audio files with relative URLs. The base URL is usually obtained by calling the get Document Baseor get Code Base method. The former gets theURL of the HTML page in which the applet is contained, the latter the URL of the applet’s codebase directory.

NOTE: In prior versions of Java SE, there was considerable confusion about these methods— see bug #4456393 on the Java bug parade. The documentation was finally clarified in Java SE 5.0.

Give the base URL and the file location to the getImageor get Audio Clip method. For example:

You can also call the play method of the Applet class without first loadingthe audio clip.

  • URL getDocumentBase()
    gets the URL of the web page containing this applet.
  • URL getCodeBase()
    gets the URL of the codebase directory from which this applet is loaded. That is either the absolute URL of the directory referenced by the codebase attribute or the directory of the HTML file if no codebase is specified.
  • void play(URL url)
  • void play(URL url, String name)
    The first form plays an audio file specified by the URL. The second form uses the string to provide a path relative to the URL in the first parameter. Nothing happens if the audio clip cannot be found.
  • AudioClipgetAudioClip(URL url)
  • AudioClipgetAudioClip(URL url, String name)
    The first form gets an audio clip from the given URL. The second form uses the string to provide a path relative to the URL in the first argument. The methods return null if the audio clip cannot be found.
  • Image getImage(URL url)
  • Image getImage(URL url, String name)
    returns an image object that encapsulates the image specified by the URL. If the image does not exist, immediately returns null. Otherwise, a separate thread is launched to load the image.

The Applet Context

An applet runs inside a browser or the applet viewer. An applet can ask the browser to do things for it, for example, fetch an audio clip, show a short message in the status line, or display a different web page. The ambient browser can carry out these requests, or it can ignore them. For example, if an applet running inside the applet viewer asks the applet viewer program to display a web page, nothing happens.

To communicate with the browser, an applet calls the getAppletContextmethod. That method returns an object that implements an interface of type AppletContext. You can think of the concrete implementation of the AppletContextinterface as a communication path between the applet and the ambient browser. In addition to getAudioClipand getImage, the Applet Context interface contains several useful methods, which we discuss in the next few sections.

Inter-Applet Communication

A web page can contain more than one applet. If a web page contains multiple applets from the same codebase, they can communicate with each other. Naturally, this is an advanced technique that you probably will not need very often.

If you give name attributes to each applet in the HTML file, you can use the getAppletmethod of the Applet Context interface to get a reference to the applet. For example, if your HTML file contains the tag

gives you a reference to the applet. What can you do with the reference? Provided you give the Chart class a method to accept new data and redraw the chart, you can call this method by making the appropriate cast.

You can also list all applets on a web page, whether or not they have a name attribute. The get Applet smethod returns an enumeration object. Here is a loop that prints the class names of all applets on the current page:

An applet cannot communicate with an applet on a different web page.

Display of Items in the Browser

You have access to two areas of the ambient browsers: the status line and the web page display area. Both use methods of the Applet Context class.

You can display a string in the status line at the bottom of the browser with the showStatus

message. For example:

TIP: In our experience, showStatusis of limited use. The browser is also using the status line, and, more often than not, it will overwrite your precious message with chatter like “Appletrunning.” Use the status line for fluff messages like “Loading data . . . please wait,” but not for something that the user cannot afford to miss.

You can tell the browser to show a different web page with the show Document method. There are several ways to do this. The simplest is with a call to showDocumentwith one argument, the URL you want to show.

The problem with this call is that it opens the new web page in the same window as your current page, thereby displacing your applet. To return to your applet, the user must click the Back button of the browser.

You can tell the browser to show the document in another window by giving a second parameter in the call to show Document. If you supply the special string " _blank", the browser opens a new window with the document, instead of displacing the current document. More important, if you take advantage of the frame feature in HTML, you can split a browser window into multiple frames, each of which has a name.

The showDocument Method

The showDocument Method

You can put your applet into one frame and have it show documents in other frames. We show you an example of how to do this in the next section.

NOTE: Sun’s applet viewer does not show web pages. The show Document method is ignored inthe applet viewer.

It’s an Applet. It’s an Application. It’s Both!

Quite a few years ago, a Saturday Night Live skit poked fun at a television commercial, showing a couple that argued about a gelatinous substance. The husband said, “It’s a dessert topping.” The wife said, “It’s a floor wax.” And the announcer concluded triumphantly, “It’s both!”

Well, in this section, we show you how to turn an applet into a Java program that is both an applet and an application. That is, you can load the program with the applet vieweror a browser, or you can start it from the command line with the java program launcher.

We are not sure how often this comes up—we found it interesting that this could be done at all and thought you would, too.

The screen show the same program, viewed inside the applet viewer as an applet and launched from the command line as an application.

It’s an applet!

It’s an applet!

It’s an application!

It’s an application!

GUI application constructs a frame object and invokes setVisible(true) on it. Since you cannot call setVisibleon a naked applet, the applet must be placed inside a frame. Weprovide a class Applet Frame whose constructor adds the applet into the content pane: public class Applet Frame extends JFrame

In the main method of the applet/application, we construct and show an AppletFrame. class My Applet Application extends MyApplet

When the applet starts, its initand start methods must be called. We achieve this by overriding the set Visible method of the Applet Frame class:

There is one catch. If the program is started as an application, and it calls get Applet Context, it gets a null pointer because it has not been launched inside a browser. This causes a runtime crash whenever we have code like

getAppletContext().showStatus(message);

While we do not want to write a full -fledged browser, we do need to supply the bare minimum to make calls like this work. The call displays no message, but at least it will not crash the program. It turns out that all we need to do is implement two interfaces:

Applet Stuband Applet Context. The major purpose of the Applet Stub interface is to locate the applet context. Every applet has an applet stub (set with the setStubmethod of the Applet class). We supply the bare minimum functionality that is necessary to implement these two interfaces.

Next, the constructor of the frame class calls setStubon the applet to make itself its stub.

Just for fun, we use the previously mentioned trick of adding the applet tag as a comment to the source file. Then, you can invoke the applet viewer with the source file without requiring an additional HTML file.

Listings below list the code. Try running both the applet and the application:



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Topics