Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Applet Basics

Java Applet Basics

An applet is a kind of Java program. It generally runs inside a Web browser that supports Java. Because it has full Java API support, an applet is a full-featured Java application.

The following shows the important differences between a standalone Java application and an applet program:


Applet Life Cycle

Four methods in the Applet class provide us with a framework on which you can develop a small program:


"Hello, World" Applet:

Below is a simple applet program, HelloWorldApplet.java:

HelloWorldApplet.java File Code:

import

java

.

applet

.*;

import

java

.

awt

.*;

public

class

HelloWorldApplet

extends

Applet

{

public

void

paint

(

Graphics

g

)

{

g

.

drawString

(

"

Hello World

"

,

25

,

50

)

;

}

}

These import statements import the following classes into our Applet class:

java

.

applet

.

Applet

.

java

.

awt

.

Graphics

.

Without these import statements, the Java compiler would not recognize the Applet and Graphics classes.


Applet Class

Every applet is a subclass of the java.applet.Applet class. The base Applet class provides methods for derived classes to call in order to obtain browser context information and services.

These methods do the following:

In addition, the Applet class provides an interface for the Viewer or browser to obtain the applet's information and to control the applet's execution.

The Viewer may be:

The Applet class provides default implementations of these methods, which can be overridden when needed.

The "Hello, World" applet is written according to the standard. The only method overridden is the paint method.


Invoking the Applet

An applet is a kind of Java program. It generally runs inside a Web browser that supports Java. Because it has full Java API support, an applet is a full-featured Java application.

The tag is the basis for embedding an applet in an HTML file. The following is an example of invoking the "Hello World" applet;

HTML code:

<
html
<
title

The Hello, World Applet

title

<
hr
<
applet
code
=
"
HelloWorldApplet.class
"
width
=
"
320
"
height
=
"
120
"

If your browser was Java-enabled, a "Hello, World" message would appear here.

applet

<
hr
html

** Note: ** You can refer to the HTML Applet tag to learn more about how to invoke an applet from HTML.

The attributes of the tag specify the applet class to run. width and height specify the initial size of the applet's running panel. The applet must use the tag to close.

If the applet accepts parameters, then the parameter values need to be placed in the tag, which is located between and the and tags. The browser ignores the text and other tags between the applet tags.

Browsers that do not support Java cannot execute and the tag. Therefore, anything displayed between the tags that is unrelated to the applet is visible in browsers that do not support Java.

The Viewer or browser looks for the compiled Java code at the document's location; to specify the document's path, you must use the codebase attribute of the tag.

As shown below:




    

If the applet is in a package rather than the default package, then the package must be specified in the code attribute, for example:




    

Getting applet parameters

The example below demonstrates how to use an applet response to set parameters specified in a file. The applet displays a black checkerboard pattern and a second color.

The second color and the size of each column are specified by the applet's parameters in the document.

CheckerApplet gets its parameters in the init() method. It can also get its parameters in the paint() method. However, it is convenient and efficient for the applet to get the values and save the settings at start rather than getting them on every refresh.

The Applet viewer or browser calls the init() method every time the applet runs. After the applet is loaded, the Viewer immediately calls the init() method (Applet.init() does nothing); override the default implementation of this method to add some custom initialization code.

The Applet.getParameter() method obtains the parameter value by giving the parameter name. If the obtained value is a number or other non-character data, it must be parsed into a string type.

The following is a modification of CheckerApplet.java:

CheckerApplet.java File Code:

import

java

.

applet

.*;

import

java

.

awt

.*;

public

class

CheckerApplet

extends

Applet

{

int

squareSize

=

50

;

//

Initialize the default size

public

void

init

(

)

{

}

private

void

parseSquareSize

(

String

param

)

{

}

private

Color

parseColor

(

String

param

)

{

}

public

void

paint

(

Graphics

g

)

{

}

}

Below are the init() method of the CheckerApplet class and the private parseSquareSize() method:

public

void

init

(

)

{

String

squareSizeParam

=

getParameter

(

"

squareSize

"

)

;

parseSquareSize

(

squareSizeParam

)

;

String

colorParam

=

getParameter

(

"

color

"

)

;

Color

fg

=

parseColor

(

colorParam

)

;

setBackground

(

Color

.

black

)

;

setForeground

(

fg

)

;

}

private

void

parseSquareSize

(

String

param

)

{

if

(

param

==

null

)

return

;

try

{

squareSize

=

Integer

.

parseInt

(

param

)

;

}

catch

(

Exception

e

)

{

//

Keep the default value

}

}

The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the library method Integer.parseInt(), which parses a string into an integer; when the parameter is invalid, Integer.parseInt() throws an exception.

Therefore, the parseSquareSize() method also catches exceptions and does not allow the applet to accept invalid input.

The applet calls parseColor() to parse the color parameter into a Color value. The parseColor() method performs a series of string comparisons to match the parameter value with predefined color names. You need to implement these methods to make the applet work.


Specifying applet parameters

The following example is an HTML file that embeds the CheckerApplet class. The HTML file uses the tag to specify two parameters for the applet.

<
html
<
title

Checkerboard Applet

title

<
hr
<
applet
code
=
"
CheckerApplet.class
"
width
=
"
480
"
height
=
"
320
"
<
param
name
=
"
color
"
value
=
"
blue
"
<
param
name
=
"
squaresize
"
value
=
"
30
"
applet
<
hr
html

** Note: ** Parameter names are case-insensitive.


Converting an Application to an Applet

Converting a graphical Java application (that is, an application that uses AWT and is launched with the java program launcher) into an applet embedded in a web page is quite simple.

The following are the steps to convert an application to an applet:

  • Write an HTML page that has a tag capable of loading the applet code.
  • Write a subclass of the JApplet class and set it as public. Otherwise, the applet cannot be loaded.
  • Eliminate the application's main() method. Do not construct a frame window for the application, because your application is to be displayed in the browser.
  • Move the initialization code from the frame window's constructor in the application into the applet's init() method. You do not need to explicitly construct the applet object; the browser will instantiate an object by calling the init() method.
  • Remove the call to the setSize() method; for an applet, the size is already set via the width and height parameters in the HTML file.
  • Remove the call to the setDefaultCloseOperation() method. An applet cannot be closed; it terminates as the browser exits.
  • If the application calls the setTitle() method, eliminate that call. An applet cannot have a title bar. (Of course, you can name the web page itself via the HTML title tag.)
  • Do not call setVisible(true); an applet is displayed automatically.

Event Handling

The Applet class inherits many event-handling methods from the Container class. The Container class defines several methods, such as processKeyEvent() and processMouseEvent(), to handle specific types of events, and a method called processEvent that captures all events.

To respond to an event, the applet must override the appropriate event-handling method.

ExampleEventHandling.java File Code:

import

java

.

awt

.

event

.

MouseListener

;

import

java

.

awt

.

event

.

MouseEvent

;

import

java

.

applet

.

Applet

;

import

java

.

awt

.

Graphics

;

public

class

ExampleEventHandling

extends

Applet

implements

MouseListener

{

StringBuffer

strBuffer

;

public

void

init

(

)

{

addMouseListener

(

this

)

;

strBuffer

=

new

StringBuffer

(

)

;

addItem

(

"

initializing the applet

"

)

;

}

public

void

start

(

)

{

addItem

(

"

starting the applet

"

)

;

}

public

void

stop

(

)

{

addItem

(

"

stopping the applet

"

)

;

}

public

void

destroy

(

)

{

addItem

(

"

unloading the applet

"

)

;

}

void

addItem

(

String

word

)

{

System

.

out

.

println

(

word

)

;

strBuffer

.

append

(

word

)

;

repaint

(

)

;

}

public

void

paint

(

Graphics

g

)

{

//

Draw a Rectangle around the applet's display area.

g

.

drawRect

(

0

,

0

,

getWidth

(

)

1

,

getHeight

(

)

1

)

;

//

display the string inside the rectangle.

g

.

drawString

(

strBuffer

.

toString

(

)

,

10

,

20

)

;

}

public

void

mouseEntered

(

MouseEvent

event

)

{

}

public

void

mouseExited

(

MouseEvent

event

)

{

}

public

void

mousePressed

(

MouseEvent

event

)

{

}

public

void

mouseReleased

(

MouseEvent

event

)

{

}

public

void

mouseClicked

(

MouseEvent

event

)

{

addItem

(

"

mouse clicked!

"

)

;

}

}

Invoke the applet as follows:

<
html
<
title

Event Handling

title

<
hr
<
applet
code
=
"
ExampleEventHandling.class
"
width
=
"
300
"
height
=
"
300
"
applet
<
hr
html

When first run, the applet displays "initializing the applet. Starting the applet.", and then when you click the rectangle, it displays "mouse clicked".


Displaying an Image

An applet can display images in formats such as GIF, JPEG, and BMP. To display an image in an applet, you need to use the drawImage() method of the java.awt.Graphics class.

The following example demonstrates all the steps to display an image:

ImageDemo.java File Code:

import

java

.

applet

.*;

import

java

.

awt

.*;

import

java

.

net

.*;

public

class

ImageDemo

extends

Applet

{

private

Image

image

;

private

AppletContext

context

;

public

void

init

(

)

{

context

=

this

.

getAppletContext

(

)

;

String

imageURL

=

this

.

getParameter

(

"

image

"

)

;

if

(

imageURL

==

null

)

{

imageURL

=

"

java.jpg

"

;

}

try

{

URL

url

=

new

URL

(

this

.

getDocumentBase

(

)

,

imageURL

)

;

image

=

context

.

getImage

(

url

)

;

}

catch

(

MalformedURLException

e

)

{

e

.

printStackTrace

(

)

;

//

Display in browser status bar

context

.

showStatus

(

"

Could not load image!

"

)

;

}

}

public

void

paint

(

Graphics

g

)

{

context

.

showStatus

(

"

Displaying image

"

)

;

g

.

drawImage

(

image

,

0

,

0

,

200

,

84

,

null

)

;

g

.

drawString

(

"

www.javalicense.com

"

,

35

,

100

)

;

}

}

Invoke the applet as follows:

<
html
<
title

The ImageDemo applet

title

<
hr
<
applet
code
=
"
ImageDemo.class
"
width
=
"
300
"
height
=
"
200
"
<
param
name
=
"
image
"
value
=
"
java.jpg
"
applet
<
hr
html

An applet can play audio by using the AudioClip interface in the java.applet package. The AudioClip interface defines three methods:

  • ** public void play():** Plays the audio clip once from the beginning.
  • ** public void loop(): ** Plays the audio clip in a loop
  • ** public void stop(): ** Stops playing the audio clip

To obtain an AudioClip object, you must call the Applet class's getAudioClip() method. This method returns immediately regardless of whether the URL points to a real audio file.

The audio file is not downloaded until it needs to be played.

The following example demonstrates all the steps to play audio:

AudioDemo.java File Code:

import

java

.

applet

.*;

import

java

.

awt

.*;

import

java

.

net

.*;

public

class

AudioDemo

extends

Applet

{

private

AudioClip

clip

;

private

AppletContext

context

;

public

void

init

(

)

{

context

=

this

.

getAppletContext

(

)

;

String

audioURL

=

this

.

getParameter

(

"

audio

"

)

;

if

(

audioURL

==

null

)

{

audioURL

=

"

default.au

"

;

}

try

{

URL

url

=

new

URL

(

this

.

getDocumentBase

(

)

,

audioURL

)

;

clip

=

context

.

getAudioClip

(

url

)

;

}

catch

(

MalformedURLException

e

)

{

e

.

printStackTrace

(

)

;

context

.

showStatus

(

"

Could not load audio file!

"

)

;

}

}

public

void

start

(

)

{

if

(

clip

!=

null

)

{

clip

.

loop

(

)

;

}

}

public

void

stop

(

)

{

if

(

clip

!=

null

)

{

clip

.

stop

(

)

;

}

}

}

Invoke the applet as follows:

<
html
<
title

The ImageDemo applet

title

<
hr
<
applet
code
=
"
ImageDemo.class
"
width
=
"
0
"
height
=
"
0
"
<
param
name
=
"
audio
"
value
=
"
test.wav
"
applet
<
hr

You can use test.wav on your computer to test the example above.