Maharaja Agrasen Institute of Technology
CIC-212 Java Programming
Lecture
Applets
What Are
Applets?
An applet is a special Java program that
can be embedded in HTML documents.
It is automatically executed by (applet-
enabled) web browsers.
In Java, non-applet programs are called
applications.
2
Application vs.
Applet
Application
Trusted (i.e., has full access to system resources)
Invoked by Java Virtual Machine (JVM, java), e.g.,
java HelloWorld
Should contain a main method, i.e.,
public static void main(String[])
Applet
Remote applets are Not trusted (i.e., has limited
access to system resource to prevent security
breaches)
Invoked automatically by the web browser
Should be a subclass of class java.applet.Applet
3
Java
Applets
Built using one of general definitions of
applets
Appletclass
JAapplet class
Java applets are usually graphical
Draw graphics in a defined screen area
Enable user interaction with GUI elements
4
Java Applet
Classes
Abstract Windowing Toolkit AWT
Earlier versions of Java
Applet class is one of the AWT components
Java Foundation Classes JFC
Extension to Java in 1997
Has a collection of Swing components for enhanced
GUIs
Swing component classes begin with J
5
Java
Applets
Applets are Java programs that can be
embedded in HTML documents
To run an applet you must create a .html file
which references the applet
Ready to Program also will run an applet
When browser loads Web page containing
applet
Applet downloads into Web browser
begins execution
Can be tested using appletviewer program
6
Applet
Declaration
Syntax (note difference from application
declaration)
public class ClassName extends Japplet/Applet
ClassName is an
object that will be a
subclass of JApplet
7
Body of an
Applet
Note there is no main() method in an applet
Japplet/Applet class provides other methods
instead of a main method
First method executed is the init() method
8
Graphics
Coordinate
(0,0) x
height
width
9
Running An
Applet
import
import java.applet.Applet;
java.applet.Applet;
import
import java.awt.Graphics;
java.awt.Graphics;
public
public class
class HelloApplet
HelloApplet extends
extends Applet
Applet {{
public
public void
void paint
paint (Graphics
(Graphics g)
g)
{{
g.drawString
g.drawString ("Hello.
("Hello. Welcome
Welcome to",25,25);
to",25,25);
g.drawString
g.drawString ("Java
("Java Programming",25,40);
Programming",25,40);
}}
}}
•• Enter
Enterthis
thistext
textinto
intoyour
your
Ready
ReadytotoProgram
Program editor
editor
•• Compile
Compilethe
theJava
Javacode
code
10
Running An
Applet
Now create an .html file to run the
applet
<html>
<html>
<applet
<applet code
code == "HelloApplet.class"
"HelloApplet.class" width=275,
width=275, height
height == 100>
100>
</applet>
</applet>
</html>
</html>
Save it as HelloApplet.html
Make sure you save it in the same
directory as the .java file
11
Running An
Applet
import allows us to use
predefined classes (allowing
us to use applets and
graphics, in this case).
extends allows us to inherit the
capabilities of class JApplet.
Method paint is guaranteed to
be called in all applets. Its first
line must be defined as above.
12
Running An
Applet
Now create an .html file to run the
applet
<html>
<html>
<applet
<applet code
code == "HelloApplet.class"
"HelloApplet.class" width=275,
width=275, height
height == 100>
100>
</applet>
</applet>
</html>
</html>
Save it as HelloApplet.html
Make sure you save it in the same
directory as the .java file
13
First Java
Applet
Java source in HelloWorldApplet.java
import java.awt.*;
import java.applet.Applet;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.BLACK);
g.fillRect(0, 0, d.width, d.height); // paint background
g.setFont(new Font("San-serif", Font.BOLD, 24));
g.setColor(new Color(255, 215,0));
g.drawString("Hello, world!", 60, 40);
g.drawImage(getImage(getCodeBase(), “Rabbit.jpg"),
20, 60, this);
}
}
14
Embedding Applet into
HTML
HTML source in HelloWorld.html
<!--HelloWorld.html-->
<html>
<head>
<title>HelloWord</title>
</head>
<body>
<center>
<applet code="HelloWorldApplet.class" width=300 height=350></applet>
</center>
<hr/>
<a href="HelloWorldApplet.java">The source.</a>
</body>
</html>
15
Compiling and
Running
To compile
javac HelloWorldApplet.java
Produces HelloWorldApplet.class
To run
Open page HelloWorld.htmlfrom web browser
or
Use appletviewer of JDK
appletviewer HelloWorld.html
16
The genealogy of
Applet
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet
|
+----
Javax.swing.JApplet
Methods are called in this
order
init and destroy are only
init()
called once
start() start and stop are called
whenever the browser enters
and leaves the page
do some work
do some work is code called
stop() by your listeners
paint is called when the
destroy() applet needs to be repainted
Applet methods
public void init ()
public void start ()
public void stop ()
public void destroy ()
public void paint (Graphics)
Also:
public void repaint()
public void update (Graphics)
public void showStatus(String)
public String getParameter(String)
Applet Life
Cycle
20
Why an applet
works
You write an applet by extending the class
Applet.
Applet defines methods init( ), start( ), stop(
), paint(Graphics), destroy( ).
These methods do nothing--they are stubs.
You make the applet do something by
overriding these methods.
public void init
()
This is the first method to execute.
It is an ideal place to initialize variables.
It is the best place to define the GUI
Components (buttons, text fields, scrollbars,
etc.), lay them out, and add listeners to them.
Almost every applet you ever write will have an
init( ) method.
public void
start ( )
Not always needed.
Called after init( ).
Called each time the page is loaded and
restarted.
Used mostly in conjunction with stop( ).
start() and stop( ) are used when the Applet
is doing time-consuming calculations that you
don’t want to continue when the page is not in
front.
public void
stop( )
Not always needed.
Called when the browser leaves the page.
Called just before destroy( ).
Use stop( ) if the applet is doing heavy
computation that you don’t want to continue
when the browser is on some other page.
Used mostly in conjunction with start()
public void
destroy( )
Seldom needed.
Called after stop( ).
Use to explicitly release system resources (like
threads).
System resources are usually released
automatically.
public void
paint(Graphics g)
Needed if you do any drawing or painting other
than just using standard GUI Components.
Any painting you want to do should be done
here, or in a method you call from here.
Painting that you do in other methods may or
may not happen.
Never call paint(Graphics), call repaint( ).
repaint(
)
Call repaint( ) when you have changed
something and want your changes to show up
on the screen
repaint( ) is a request--it might not happen
When you call repaint( ), Java schedules a
call to update(Graphics g)
)
When you call repaint( ), Java schedules a call
to update(Graphics g)
Here's what update does:
public void update(Graphics g)
{
// Fills applet with background color, then
paint(g);
}
Sample Graphics
methods
A Graphics is something you can paint on
g.drawString(“Hello”, 20, 20); Hello
g.drawRect(x, y, width,
height);
g.fillRect(x, y, width,
height);
g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
g.setColor(Color.red);
L
<html>
<head>
<title> Hi World Applet </title>
</head>
<body>
<applet code="HiWorld.class”
width=300 height=200>
<param name="arraysize"
value="10">
</applet>
</body>
</html>
L
<param name="arraysize"
value="10">
public String getParameter(String name)
String s = getParameter("arraysize");
try { size = Integer.parseInt (s) }
catch (NumberFormatException e) {…}
Example
1
Adding two Floating point
numbers.
32
Numbers
1 // Fig. 3.13: AdditionApplet.java
2 // Adding two floating-point numbers.
3
4 // Java packages
5 import java.awt.Graphics; // import class Graphics
6 import javax.swing.*; // import package javax.swing
7
8 public class AdditionApplet extends JApplet {
9 double sum; // sum of values entered by user * allows any class in the
10
11 // initialize applet by obtaining values from user
package to be used.
12 public void init()
13 {
14 String firstNumber; // first string entered by user
15 String secondNumber; // second string entered by user
16
17 double number1; // first number to add
18 double number2; // second number to add
19 Field sum may be used anywhere
20 // obtain first number from user
21 firstNumber = JOptionPane.showInputDialog(
in the class, even in other
22 "Enter first floating-point value" ); methods.
23
Type double can store floating
24 // obtain second number from user
25 secondNumber = JOptionPane.showInputDialog( point numbers.
26 "Enter second floating-point value" );
27
28 // convert numbers from type String to type double
29 number1 = Double.parseDouble( firstNumber );
30 number2 = Double.parseDouble( secondNumber );
31
Numbers
32 // add numbers
33 sum = number1 + number2;
34
35 } // end method init
36
37 // draw results in a rectangle on applet’s background
38 public void paint( Graphics g )
39 {
40 // call superclass version of method paint
41 super.paint( g );
42
43 // draw rectangle starting from (15, 10) that is 270
44 // pixels wide and 20 pixels tall
45 g.drawRect( 15, 10, 270, 20 );
46
47 // draw results as a String at (25, 25)
48 g.drawString( "The sum is " + sum, 25, 25 );
49
50 } // end method paint
51 drawRect takes the upper left coordinate, width,
52 } // end class AdditionApplet and height of the rectangle to draw.
1 <html>
2 <applet code = "AdditionApplet.class" width = "300" height = "65">
3 </applet>
4 </html>
Numbers
35
Numbers
Lines 1-2: Comments
5 import java.awt.Graphics; // import class Graphics
Line 5: imports class Graphics
import not needed if use full package and class name
public void paint ( java.awt.Graphics g )
6 import javax.swing.*; // import package javax.swing
Line 6: specify entire javax.swing package
* indicates all classes in javax.swing are
available
Includes JApplet and JOptionPane
Use JOptionPane instead of
javax.swing.JOptionPane
* does not load all classes
Compiler only loads classes it uses
36
Numbers
8 public class AdditionApplet extends JApplet {
Begin class declaration
Extend JApplet, imported from package
javax.swing
9 double sum; // sum of values entered by user
Field declaration
Each object of class gets own copy of the field
Declared in body of class, but not inside
methods
Variables declared in methods are local variables
Can only be used in body of method
Fields can be used anywhere in class
Have default value (0.0 in this case)
37
Numbers
9 double sum; // sum of values entered by user
Primitive type double
Used to store floating point (decimal) numbers
12 public void init()
Method init
Normally initializes fields and applet class
Guaranteed to be first method called in applet
First line must always appear as above
Returns nothing (void), takes no arguments
13 {
Begins body of method init
38
Numbers
14 String firstNumber; // first string entered by user
15 String secondNumber; // second string entered by user
16
17 double number1; // first number to add
18 double number2; // second number to add
Declare variables
Two types of variables
Reference variables (called references)
Refer to objects (contain location in memory)
Objects defined in a class definition
Can contain multiple data and methods
paint receives a reference called g to a
Graphics object
Reference used to call methods on the Graphics
object
Primitive types (called variables)
Contain one piece of data
39
Numbers
14 String firstNumber; // first string entered by user
15 String secondNumber; // second string entered by user
16
17 double number1; // first number to add
18 double number2; // second number to add
Distinguishing references and variables
If type is a class name, then reference
String is a class
firstNumber, secondNumber
If type a primitive type, then variable
double is a primitive type
number1, number2
40
Numbers
21 firstNumber = JOptionPane.showInputDialog(
22 "Enter first floating-point value" );
Method
JOptionPane.showInputDialog
Prompts user for input with string
Enter value in text field, click OK
If not of correct type, error occurs
In Chapter 15 learn how to deal with this
Returns string user inputs
Assignment statement to string
Lines
25-26: As above, assigns input to
secondNumber
41
Numbers
29 number1 = Double.parseDouble( firstNumber );
30 number2 = Double.parseDouble( secondNumber );
static method Double.parseDouble
Converts String argument to a double
Returns the double value
Remember static method syntax
ClassName.methodName( arguments )
33 sum = number1 + number2;
Assignment statement
sum an field, can use anywhere in class
Not defined in init but still used
42
Numbers
35 } // end method init
Ends method init
appletviewer (or browser) calls inherited
method start
start usually used with multithreading
Advanced concept, in Chapter 16
We do not declare it, so empty declaration in
JApplet used
Next, method paint called
45 g.drawRect( 15, 10, 270, 20 );
Method drawRect( x1, y1, width, height )
Draw rectangle, upper left corner (x1, y1),
specified width and height
Line 45 draws rectangle starting at (15, 10) with
43 a width of 270 pixels and a height of 20 pixels
Numbers
48 g.drawString( "The sum is " + sum, 25, 25 );
SendsdrawString message (calls method)
to Graphics object using reference g
"The sum is" + sum - string concatenation
sum converted to a string
sum can be used, even though not defined in
paint
field, can be used anywhere in class
Non-local variable
44
Example -
2
To draw a face
45
Face
46
Interactive Input
How to load media and text
URL getDocumentBase() – Directory from which HTML file
is loaded.
URL getCodeBase() - Directory from which .class file is
loaded.
showDocument() – to load another file from current Applet
getAppletContext() – to get current applet environment.
AudipClip getAudioClip(URL u) – Returns an AudioClip
object (play(), stop(), loop())
Image getImage(URL u) – Returns an image object
Void showStatus(String str) – display str in status window
47
Example- 3: To load another
file from Applet
import java.awt.*;
import java.applet.*;
import java.net.*;
public class Acdemo extends Applet{
public void start()
{
AppletContext ac= getAppletContext();
URL url = getCodeBase();
try
{
ac.showDocument( new URL(url + “Test.html”));
}catch(MalformedURLException e) { showStatus(“URL not found”);}
}
}
48
Applet
49
-4
To create Digital Clock
50
Animation Applet --- Digital
Clock
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;
public class DigitalClock extends java.applet.Applet
{
<Fields>
<Methods>
}
51
Program
Structure
java.applet.Applet
DigitalClock 1
javax.swing.Timer
+ start(): void
+ stop(): void <<use>>
+ paint(g: Graphics) : void java.util.Calendar
<<use>> <<use>>
java.awt java.awt.event
52
Field
Declarations
protected Timer timer;
protected Font font =
new Font("Monospaced", Font.BOLD, 48);
protected Color color = Color.GREEN;
53
Object
Initialization
public DigitalClock()
{
timer = new Timer(1000, createTimerTickHandler());
}
protected ActionListener createTimerTickHandler()
{
return new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
repaint();
}
};
}
54
The start() and stop()
Methods
public void start()
{
timer.start();
}
public void stop()
{
timer.stop();
}
Start and stop the timer
Stopped timer will not consume CPU time.
55
The paint()
Method
public void paint(Graphics g)
{
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
g.setFont(font);
g.setColor(color);
g.drawString(hour / 10 + hour % 10 +
":" + minute / 10 + minute % 10 +
":" + second / 10 + second % 10,
10, 60);
}
56
Who Calls the
paint()method?
Timer ticks and calls
ActionListener.actionPerformed()
ActionListener.actionPerformed()
calls DigitalClock.repaint()
DigitalClock.repaint() calls
DigitalClock.paint()
The paint() method is usually not called
directly.
57
HTML
Source
<!-- DigitalClock.html -->
<html>
<head>
<title>Digital Clock Applet</title>
</head>
<body bgcolor=black>
<h1>The Digital Clock Applet</h1><p>
<applet code=DigitalClock.class width=250 height=80>
</applet>
<p><hr>
<a href=DigitalClock.java>The source</a>
</body>
</html>
58