Chapter-Two
Java Applet
BY:
Andargie Mekonnen
Java Applet Basics
Note:[Link] package package has been deprecated in Java 9 and later versions,as applets are no longer widely
used on the web.
Throwback of making GUI application:
Java was launched on 23-Jan-1996(JDK 1.0) and at that time it only supported CUI(Character User Interface)
application.
But in 1996 VB(Visual Basic) of Microsoft was preferred for GUI programming.
So the Java developers in hurry(i.e within 7 days) have given the support for GUI from Operating System(OS).
Now, the components like button, etc. were platform-dependent(i.e in each platform there will be different size, shape
button).
But they did the intersection of such components from all platforms and gave a small library which contains these
intersections and it is available in AWT(Abstract Window Toolkit) technology but it doesn’t have advanced features
like dialogue box, etc.
11/18/2024 Andargie Mekonnen 2
Java Applet Basics
Now to run Applet, java needs a browser and at that time only “Internet Explorer” was there of
Microsoft but Microsoft believes in monopoly.
So “SUN Micro-System”(the company which developed Java) contracted with other company
known as “Netscape”(which developed Java Script) and now the “Netscape” company is also
known as “Mozilla Firefox” which we all know is a browser.
Now, these two companies have developed a technology called “SWING” and the benefit is that
the SWING components are produced by Java itself.
Therefore now it is platform-independent as well as some additional features have also been
added which were not in AWT technology.
So we can say that SWING is much more advanced as compared to AWT technology.
11/18/2024 Andargie Mekonnen 3
What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web browser
and works at client side.
An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web
server. Applets are used to make the website more dynamic and entertaining.
Important points :
All applets are sub-classes (either directly or indirectly) of [Link] class.
Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.
In general, execution of an applet does not begin at main() method.
Output of an applet window is not performed by [Link](). Rather it is handled with
various AWT methods, such as drawString().
11/18/2024 Andargie Mekonnen 4
Java Applet Methods
Life cycle of an applet : Life cycle of an applet :
When an applet begins, the following methods
are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following
sequence of method calls takes place:
1. stop( )
2. destroy( )
11/18/2024 Andargie Mekonnen 5
Java Applet Methods
init( ) : The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
start( ) : The start( ) method is called after init( ). It is also called to restart an applet after
it has been stopped.
Note that init( ) is called once i.e. when the first time an applet is loaded whereas start( )
is called each time an applet’s HTML document is displayed onscreen. So, if a user
leaves a web page and comes back, the applet resumes execution at start( ).
11/18/2024 Andargie Mekonnen 6
Java Applet Methods
paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
11/18/2024 Andargie Mekonnen 7
Java Applet Methods
Note: This is the only method among all the method mention above, which is parameterized.
It’s prototype is
public void paint(Graphics g)
where g is an object reference of class Graphic.
Now the Question Arises:
In the prototype of paint() method, we have created an object reference without creating its
object. But how is it possible to create object reference without creating its object?
Ans. Whenever we pass object reference in arguments then the object will be provided by its
caller itself. In this case the caller of paint() method is browser, so it will provide an object.
The same thing happens when we create a very basic program in normal Java programs. For
Example: public static void main(String []args){}
11/18/2024 Andargie Mekonnen 8
Java Applet Methods
Here we have created an object reference without creating its object but it still runs because
it’s caller,i.e JVM will provide it with an object.
stop( ) : The stop( ) method is called when a web browser leaves the HTML document
containing the applet—when it goes to another page, for example. When stop( ) is called, the
applet is probably running. You should use stop( ) to suspend threads that don’t need to run
when the applet is not visible. You can restart them when start( ) is called if the user returns
to the page.
destroy( ) : The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
11/18/2024 Andargie Mekonnen 9
Java Applet Methods
import [Link];
import [Link];
// HelloWorld class extends Applet
public class HelloWorld extends Applet
// Overriding paint() method
@Override
public void paint(Graphics g)
[Link]("Hello World", 20, 20); }}
11/18/2024 Andargie Mekonnen 10
Java Applet Methods
Explanation:
The above java program begins with two import statements. The first import statement imports
the Applet class from applet package.
Every AWT-based(Abstract Window Toolkit) applet that you create must be a subclass (either
directly or indirectly) of Applet class. The second statement import the Graphics class from AWT
package.
The next line in the program declares the class HelloWorld.
11/18/2024 Andargie Mekonnen 11
Java Applet Methods
This class must be declared as public because it will be accessed by code that is outside the
program.
Inside HelloWorld, paint( ) is declared.
This method is defined by the AWT and must be overridden by the applet.
Inside paint( ) is a call to drawString( ), which is a member of the Graphics class.
Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method
outputs a string beginning at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y)
11/18/2024 Andargie Mekonnen 12
Java Applet Methods
Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner
is location 0,0. The call to drawString( ) in the applet causes the message “Hello World” to be
displayed beginning at location 20,20.
Notice that the applet does not have a main( ) method. Unlike Java programs, applets do not
begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an
applet begins execution when the name of its class is passed to an applet viewer or to a network
browser.
11/18/2024 Andargie Mekonnen 13
Java Applet Methods
Running the HelloWorld Applet :
After you enter the source code for [Link], compile in the same way that you have
been compiling java programs(using javac command). However, running HelloWorld with the
java command will generate an error because it is not an application.
Java HelloWorld
Error: Main method not found in class HelloWorld,
please define the main method as:
public static void main(String[] args)
11/18/2024 Andargie Mekonnen 14
Java Applet Methods
There are two standard ways in which you can run an applet :
Using java enabled web browser : To execute an applet in a web browser we have to write a
short HTML text file that contains a tag that loads the applet. We can use APPLET or
OBJECT tag for this purpose. Using APPLET, here is the HTML file that executes
HelloWorld :
<applet code="HelloWorld" width=200 height=60> </applet>
The width and height statements specify the dimensions of the display area used by the
applet. The APPLET tag contains several other options. After you create this html file, you
can use it to execute the applet.
NOTE : Chrome and Firefox no longer supports NPAPI (technology required for Java
applets).
11/18/2024 Andargie Mekonnen 15
Java Applet Methods
Using an applet viewer, such as the standard tool, applet-viewer. An applet
viewer executes your applet in a window. This is generally the fastest and
easiest way to test your applet.
To execute HelloWorld with an applet viewer, you may also execute the HTML file shown earlier.
For example, if the preceding HTML file is saved with
[Link], then the following command line will run HelloWorld :
appletviewer [Link]
11/18/2024 Andargie Mekonnen 16
Java Applet Methods
appletviewer with java source file : If you include a comment at the head of your Java source
code file that contains the APPLET tag then your code is documented with a prototype of the
necessary HTML statements, and you can run your compiled applet merely by starting the applet
viewer with your Java source code file. If you use this method, the HelloWorld source file looks
like this :
11/18/2024 Andargie Mekonnen 17
Java Applet Methods
//code to illustrate paint public class GFG extends Applet
//method gets called again {
//and again public void paint(Graphics g)
import [Link].*;// used {
//to access showStatus() Date dt = new Date();
import [Link].*;//Graphic [Link]("Today is" + dt);
//class is available in this package //in this line, super keyword is
import [Link];// used // avoidable too. } }
//to access Date object
11/18/2024 Andargie Mekonnen 18
Java Applet Methods
With this approach, first compile [Link] file and then simply run the below command to
run applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
To prove this, let’s first study what is “Status Bar” in Applet:
“Status Bar” is available in the left bottom window of an applet. To use the status bar and write
something in it, we use method showStatus() whose prototype is
public void showStatus(String)
By default status bar shows “Applet Started” By default background color is white.
To prove paint() method is called again and again, here is the code:
11/18/2024 Andargie Mekonnen 19
Java Applet Methods
//code to illustrate paint //to access showStatus()
//method gets called again import [Link].*;//Graphic
//and again
//class is available in this package
import [Link].*;// used public class GFG extends
import [Link];// used
Applet {
//to access Date object
public void paint(Graphics g)
{ public class GFG extends Applet {
Date dt = new Date(); public void paint(Graphics g) {
[Link]("Today is" + dt); Date dt = new Date();
//in this line, super keyword is
[Link]("Today is" + dt); //in this line, super
// avoidable too. } } keyword is avoidable too. } }
11/18/2024 Andargie Mekonnen 20
Java Applet Methods
Note:- Here we can see that if the screen is maximized or minimized we will get an
updated time. This shows that paint() is called again and again.
Features of Applets over HTML
Displaying dynamic web pages of a web application.
Playing sound files.
Displaying documents
Playing animations
11/18/2024 Andargie Mekonnen 21
Java Applet Methods
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets:
An applet cannot load libraries or define native methods.
An applet cannot ordinarily read or write files on the execution host.
An applet cannot read certain system properties.
An applet cannot make network connections except to the host that it came from.
An applet cannot start any program on the host that’s executing it.
11/18/2024 Andargie Mekonnen 22
Java Applet Methods
Displaying Graphics in Applet
[Link] class provides many methods for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
11/18/2024 Andargie Mekonnen 23
Java Applet Methods
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
11/18/2024 Andargie Mekonnen 24
Java Applet Methods
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to
the specified font.
11/18/2024 Andargie Mekonnen 25
Java Applet Methods
11/18/2024 Andargie Mekonnen 26
Java Applet Methods
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be displayed. The [Link] class provide a method drawImage() to display
the image.
Syntax of drawImage() method:
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image
11/18/2024 Andargie Mekonnen 27
Java Applet Methods
How to get the object of Image:
The [Link] class provides getImage() method that returns the object of
Image. Syntax:
public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
public URL getCodeBase(): is used to return the base URL.
11/18/2024 Andargie Mekonnen 28
Java Applet Methods
11/18/2024 Andargie Mekonnen 29
Java Applet Methods
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is
required to be moved.
11/18/2024 Andargie Mekonnen 30
Java Applet Methods
Example of animation in applet:
import [Link].*;
import [Link].*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
[Link](picture, i,30, this);
try{[Link](100);}catch(Exception e){}
}
}
}
11/18/2024 Andargie Mekonnen 31
Java Applet Methods
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object.
The Component class implements ImageObserver interface. So current class object
would also be treated as ImageObserver because Applet class indirectly extends the
Component class.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
11/18/2024 Andargie Mekonnen 32
Java Applet Methods
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
Example of Painting in Applet:
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
11/18/2024 Andargie Mekonnen 33
Java Applet Methods
setBackground([Link]);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
}
public void mouseMoved(MouseEvent me){}
}
11/18/2024 Andargie Mekonnen 34
Java Applet Methods
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
11/18/2024 Andargie Mekonnen 35
Animation in applet
[Link] [Link]
import [Link].*; <html>
import [Link].*; <body>
public class AnimationExample extends Applet { <applet code="[Link]"
Image picture; width="300“ height="300">
public void init() { </applet>
picture =getImage(getDocumentBase(),"bike_1.gif"); </body>
} </html>
public void paint(Graphics g) { <html>
for(int i=0;i<500;i++){
[Link](picture, i,30, this);
try{[Link](100);}catch(Exception e){}
}
} }
11/18/2024 Andargie Mekonnen 36
EventHandling in JApplet
[Link] b=new JButton("Click");
mport [Link].*; [Link](80,150,70,40);
import [Link].*; add(b);add(tf);
import [Link].*; [Link](this);
public class EventJApplet extends JApplet implements setLayout(null);
ActionListener{
}
JButton b; public void actionPerformed(ActionEvent e){
JTextField tf; [Link]("Welcome");
public void init(){
}
tf=new JTextField(); }
[Link](30,40,150,20);
11/18/2024 Andargie Mekonnen 37
EventHandling in JApplet
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
11/18/2024 Andargie Mekonnen 38
Animation in applet
[Link]
<html>
<body>
<applet code="[Link]" width="300" height
="300">
</applet>
</body>
</html>
<html>
<body>
<applet code="[Link]" width="300" height
="300">
</applet>
</body>
</html>
11/18/2024 Andargie Mekonnen 39
11/18/2024 Andargie Mekonnen 40