Lecture 16 Applets
Lecture 16 Applets
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-
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
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
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
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).
12
Running An
Applet
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
20
Why an applet
works
<body>
<applet code="HiWorld.class”
width=300 height=200>
<param name="arraysize"
value="10">
</applet>
</body>
</html>
L
<param name="arraysize"
value="10">
String s = getParameter("arraysize");
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
javax.swing.JOptionPane
* does not load all classes
Compiler only loads classes it uses
36
Numbers
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
37
Numbers
Method init
Normally initializes fields and applet class
Guaranteed to be first method called in applet
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
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
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
Lines
25-26: As above, assigns input to
secondNumber
41
Numbers
29 number1 = Double.parseDouble( firstNumber );
30 number2 = Double.parseDouble( secondNumber );
Assignment statement
sum an field, can use anywhere in class
Not defined in init but still used
42
Numbers
35 } // end method init
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
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
50
Animation Applet --- Digital
Clock
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;
<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
53
Object
Initialization
public DigitalClock()
{
timer = new Timer(1000, createTimerTickHandler());
}
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