18 11 22 (Applet)
18 11 22 (Applet)
12.2 APPLETS
java.applet.Applet is the superclass of all the applets. Thus all the applets, directly or indirectly,
inherently use the methods of Applet belonging java.applet package. This class provides all the
necessary methods for starting, stopping, and manipulating applets. It also has methods providing
multimedia support to an applet. Applet class has a predefined hierarchy in Java, which shows
the classes extended by Applet class.
Figure 12.1 simply makes it easy for you to understand that an applet, which is a subclass of
java.applet.Applet, also inherits the methods of the other classes like java.awt.Panel, java.
awt.Container, java.awt.Component, and java.lang.Object, indirectly.
You can see that these classes are the ones which provide support for Javas window-based GUI,
thus making an applet capable of supporting window-based activities. The common methods
belonging to the Applet class are mentioned in Table 12.2.
356 Programming in Java
in Section 12.1 that unlike an application program, Java runtime system does not call the main()
method to start the execution of an applet, rather it just loads the methods of applet class which
are responsible for starting, running, stopping, and manipulating an applet. The complete life
cycle of the applet will be taken up in the next section.
There is a method, paint() in the Container class, which is inherited by Applet class (as you
can make out from Fig. 12.1), carrying the signature,
public void paint(Graphics g)
This method, when called, displays the output of applet as per the code written on the applets
panel. You can see the argument of this method; it is nothing but an object of Graphics class.
The object makes it possible for an applet to output text, graphics, sound, etc. One thing you
must remember, you cannot take the services of Graphics class unless you import the package
it belongs to, i.e., java.awt. The output operations for an applet requires the methods contained
in the Graphics class, that is why its Graphics object is passed as argument to paint(). Now that
you know some details about the internals of an applet, we can discuss the program structure
of an applet.
When an applet is first loaded, Java runtime system creates an instance of the main class,
which is FirstApplet in this case. Then the methods belonging to the Applet class are called
through this object.
import java.applet.*;
//so as to make Applet class available
}
358 Programming in Java
Explanation
L1 All applets are the subclasses of Applet class. L4 The p a in t ( ) method defined by AWT
All applets must import the java.applet package. Container class is overridden. Any output to be
L2 The applet uses the methods of java.awt shown by an applet has to be taken care by this
package; it must be imported. method only. Please note that an object of Graphics
L3 The FirstApplet class is declared public so class is passed as parameter to this method.
that the program that executes the applet (a Java- L5 The object of the Graphics class is used to
enabled browser or applet viewer, which might not invoke drawString() method, which is responsible
be local to the program) can access it. This class for printing the string (This is my First Applet) at
extends the Applet class of java.applet package, x-coordinate 10 and y-coordinate 10.
thus inheriting the features of Applet class.
Note If you wish to run the above html file in any web browser, instead of using applet viewer, you
must have Java-enabled web browser. Otherwise, you will have to install Java plug-in, which
lets you run your applets as web pages under 1.2 version of JVM instead of the web browsers
default virtual machine.
(b) Just as above, save the le as FirstApplet.java and compile it by using javac. In
order to run the applet, you have to give the below HTML coding as a comment in
FirstApplet.java.
/* <APPLET code = "FirstApplet.class" WIDTH = 200 HEIGHT = 150></APPLET> */
Applets 359
In this chapter, we will be using the second approach throughout. So Example 12.1(a) should
have been actually written as shown in Example 12.1(b).
Output
Idle
Dead
Figure 12.3 shows the flow an applet takes while moving from one state to another.
As mentioned before, an applet may override some of the basic methods of class Applet. Note
that these methods are responsible for the lifecycle of an applet. These methods are
init()
start()
stop()
destroy()
init() Loading an
BORN
Applet
start()
stop()
RUNNING IDLE
start()
destroy()
paint()
DEAD
Note In order to initialize an applet, we must override the init() method of Applet class.
Running State
Applet moves to the running state by calling start(). An applet moves to this phase automatically
after the initialization state. But if the applet is stopped or it goes to idle state, start() must be
called in order to force the applet again to the running state. Suppose you have opened a web
Applets 361
page (having an applet) and you move temporarily to another web page (by minimizing it) the
first one goes to the idle state; when you return back to the first page, start() is called to put
the applet in the running state again. Unlike init(), start() can be called more than once.
You can see the paint() method in Fig. 12.3. This method is responsible for forcing the applet
to an intermediary state (display state), which is actually a part of the running state itself. While
running, an applet may need to perform some output and display it on the panel of the applet.
The paint() method, which is a part of Container class (a superclass of Applet class), needs to
be overridden for the purpose. This method is called each time to draw and redraw the output
of an applet. We already know the drawing of output of an applet. Let us discuss redrawing the
output of an applet with an example. An applet window may be minimized and then restored.
This restoration is nothing but redrawing of applets output and could be achieved by calling
paint(). Actually when an applet in restored, start() and paint() are called in sequence. We
will revisit this method in Section 12.7.1.
Idle State
An applet goes to idle state, once it is stopped from running. If we leave a web page containing
an applet (i.e., minimize it), the applet automatically goes to idle state. An applet can also be
forced to stop or go to idle state by calling stop().
Note If a thread has been created to control an applet by overriding start(), then we must use
stop() to stop the thread, by overriding the stop() method of the Applet class.
Dead State
Terminating or stopping an applet should not be confused with destroying an applet. An applet
goes to dead state when it is destroyed by invoking the destroy() method of Applet class.
It results in complete removal of applet from the memory. Whenever we quit the browser,
destroy() is called automatically. You should free up the resources being used by applet (if any)
by overriding the destroy() method. Like init(), destroy() is also called only once. stop()
is always called before destroy().
Here, the string msg is the string output to be displayed by the applet and a, b are the x, y
coordinates respectively of the window, where the output has to be displayed.
setBackground()
This method belongs to component class. It is used to set the background color of the applet
window. Its form is
void setBackground(Color anyColor)
The above method takes the color to be set as background, as argument. The Color class has
certain predefined constants for each color, such as Color.red, Color.blue, Color. green,
and Color.pink.
setForeground()
This method is similar to setBackground method, except that these are used to set the color of
the text to be displayed on the foreground of the applet window. Its form is
void setForeground(Color anyColor)
Component class has two more methods getBackground() and getForeground(), having the
following forms:
Color getBackground();
Color getForeground();
You can very well see that these methods return the current context of the Color, showing the
background and foreground colors, respectively.
showStatus()
This method is a member of Applet class. It is used to display any string in the status window
of the browser or appletviewer. Its from is
void showStatus(String text)
Here, the argument of the method is basically the string which you want to be displayed in the
status window.
Before going any further, we should better take an example which uses these methods, discussed
until now.
Output
Explanation
L13 All the important classes (belonging to their class (part of java.awt package). In L9, the text is
respective packages), whose members are to be used initialized by a string, This is an example applet.
in the applet are imported. L1113 These lines account for the implementation
L610 This section shows the implementation of of start(), responsible for forcing the applet in
init(), where the background and foreground of running state. L13 displays the message about
the applet is set to white and red, respectively (see the start of the applet on the screen. Note that this
L78). White and red are static fields of the Color message will not be displayed on the applet window;
364 Programming in Java
it will be displayed as seen by you in earlier chapters L2023 These lines are accountable for the
(by the use of System.out.println()). implementation of paint() method. In L22,
L1416 These lines take care of the implementation Graphics object g is used to invoke its drawString()
of stop(). L16 just displays the message about method, which is actually used for writing on an
stopping an applet. As many a times you will stop the
applet window. See the arguments passed to this
applet, this message will be displayed on the screen.
method: text, which contains the string, This is
You can visualize easily that even minimizing the
applet window stops or forces the applet into idle an example applet and the x, y coordinates from
state. If restored after getting minimized, it will where this text will start in the displayable part of
again invoke start() and paint(). the applet. paint() is also called when the window
L1719 These lines take care of the implementation containing applet is covered by another window and
of destroy(). Try closing the applet window and they later uncovered. (not minimized and restored)
you will see the message Exiting the applet L22 You can see the method, showStatus() ,
(L19). Here, this message simply means that the having the text, which has to be shown in the status
applet is destroyed or has moved to the dead state. window of the applet, as argument.
If you wish that a drawing should appear in a window, you shall override either or both of the
methods. Let us discuss these methods in detail.
12.7.1 paint() Method
When a component needs to draw/redraw itself, its paint() method is called. The component
draws itself when it first becomes visible. The component paint() method is also invoked when
the window containing it is uncovered, if it is covered by another window.
The simplest paint() method looks like the following:
public void paint(Graphics g) {... }
We have discussed the Graphics object passed to the method earlier. It will be discussed in more
detail in the next chapter.
Example 12.3 Set the Color of the Applet and Draws a Fill Oval
/* <APPLET code = "FillOval.class" WIDTH = 200 HEIGHT = 200></APPLET> */
L1 import java.applet.Applet;
L2 import java.awt.Color;
L3 import java.awt.Graphics;
L4 public class FillOval extends Applet
{
L5 public void paint(Graphics g)
{
Applets 365
L6 g.setColor(Color.red);
L7 g.llOval(20, 20, 60, 60);
L8 }
L9 }
Output
Explanation
L58 These lines are accountable for the class is invoked at L7. It fills an oval bounded
implementation of paint() method. The setColor() by the specified rectangle with the current color.
method of G ra ph ics class is used to set the The parameters passed to the method are the
drawing color of the applet to red (L6). Another x-coordinate, y-coordinate, width, and height,
method, fillOval(), belonging to the Graphics respectively.
the update() method, and then the red oval will be drawn by the paint() method. A large area
of one color is first drawn and then the large area of the oval in another color (red in this case)
is redrawn. You, as a user can see some slight flickering while displaying the result, especially
if you try to draw the oval a number of times in succession.
The above problem can be overcome by overriding update(). You would override update()
to call paint(). Then this paint()will first draw only the background areas surrounding the red
oval and then draw the red oval. Obviously, the flickering problem found earlier is removed
because of elimination of the drawing of two overlapping objects of different colors.
12.7.3 repaint() Method
Sometimes you may want to force a component to be repainted manually. For example, if you
have changed certain properties of a component to reflect its new appearance, you can call the
repaint() method. Here is an example:
text.setBackground(Color.blue);
text.repaint();
repaint() in its default implementation calls update() which in turn calls paint(). repaint()
method requests the AWT to call update and it returns. The AWT combines multiple rapid repaint
requests into one request (usually this happens when you repaint inside a loop). So the last
repaint in the sequence actually causes paint(). We will discuss these topics in Chapters 13 and
14, where we will illustrate the use of repaint() with proper examples.
This is the most simplified form of APPLET tag, having only the mandatory fields as attributes.
Actually this particular tag has many more attributes which are optional but worth discussing.
The full syntax of the APPLET tag is shown below.
<APPLET [CODEBASE= codebasedURL]
CODE = appletFile [ALT= alternateText] [NAME = appletInstanceName] WIDTH
= pix els HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels]
[HSPACE = pixels]>
[<PARAM NAME = attributeName VALUE = attributeValue>]
[<PARAM NAME = attributeName VALUE = attributeValue>]
</APPLET>
Applets 367
In the above syntax, the attributes which are put inside the big braces are optional ones. Let us
discuss about the use of these attributes in detail.
Codebase Here, we may specify the URL of the directory where the executable class file
(specified by CODE attribute) of the applet will be searched for.
Code It gives the name of the file containing the applets compiled class file. It is a mandatory
attribute, which should always be present in APPLET tag.
Alt It is an attribute, which is used to specify the alternate short text message that should be
displayed in case the browser recognizes the HTML tag but cannot actually run the applet
because of some reason.
Name It is possible to give a name to an applets instance using this optional attribute. If any
other applet on the same web page wants to communicate with this applet, it is referenced
through its NAME only.
Width It gives the width of the applet display area in terms of pixels.
Height It gives the height of the applet display area in terms of pixels.
Align This optional attribute is used to set the alignment of an applet. The alignment can be
set as LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and
ABSBOTTOM.
Vspace These are used to specify the space, in pixels, above and below the applet.
Hspace These are used to specify the space, in pixels, on each side of the applet.
You can use PARAM tags between the <APPLET> and </APPLET> tags to provide information
about parameters, or arguments, to be used by the Java applet. The <PARAM> tag is simpleit
NAMES a parameter the JAVA applet needs to run, and provides a VALUE for that parameter.
Note User-defined parameters can be supplied to an applet using <PARAM .> tags.
Let us take an example applet which uses the concept of passing parameters.
L1 import java.awt.*;
L2 import java.applet.*;
368 Programming in Java
Output
Explanation
Let us start with the APPLET tag placed as comment L46 References to the String class is declared as
before the actual code for the program starts. Three name and profession in L4 and L5, respectively.
PARAM tags are between the start and close of the A variable, age, of integer type is declared in L6.
APPLET tag. All the three PARAM tags have NAME L719 Implementation of start() method is
and its corresponding VALUE, such as yourName has shown. At L9, getParameter() method returns the
the value John, yourProfession has the value consultant value of the parameter name, yourName, passed
and yourAge has the value 35. as argument. The returned value is stored in name,
L12 For importing necessary classes from their declared at L4 as string reference. Similarly, two
respective packages. more getParameter() methods are used at L11
L3 A class named as ParamPassing is declared to and L14, returning the values for the respective
extend the Applet class of the java.applet package. parameters names passed as arguments. The use of