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
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.
To execute the applet, you carry out two steps:
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
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
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:
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:
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.
then you use the following tag in MyPage.html:
(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:
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.
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
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.
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.
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.
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 showStatusmessage. 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
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 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 likegetAppletContext().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:
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.