Transcript Applet
COMP201 Java Programming
Part II: GUI Programming
Topic 11: Applets
Chapter 10
COMP201 Topic 11 / Slide 2
Outline
Introduction
Applets basics
What are applets?
How to run?
Class loader and JAR files
Security basics
Applet life cycle
Converting applications to applets
Resources for applets
Communication with browser
COMP201 Topic 11 / Slide 3
Introduction
So far, we’ve only covered topics related to
stand-alone applications
An applet is designed to run within a browser
Bring web pages to life
Reason behind hype in Java
Note: Java is not a language for designing web pages. It
is a tool for bring them to life.
COMP201 Topic 11 / Slide 4
Introduction/JApplet Class
An applet is a Java class which extends
java.applet.Applet
If Swing components are used, the applet must
extend from javax.swing.JApplet
We will only discuss applets that extend JApplet
JApplet is a sub-class of Applet, which in turn is
a subclass of Panel
Event handling exactly the same as before
COMP201 Topic 11 / Slide 5
Introduction/First Applet
public class NotHelloWorldApplet extends JApplet
{ public void init()
{
Container contentPane = getContentPane();
JLabel label = new JLabel("Not a Hello,
World applet", SwingConstants.CENTER);
contentPane.add(label);
}
} //NotHelloWorldApplet.java
COMP201 Topic 11 / Slide 6
Introduction/First Applet
Compare with
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{
setTitle("NotHelloWorld");
setSize(300, 200);
Container contentPane = getContentPane();
contentPane.add(new NotHelloWorldPanel());
}
}
public class NotHelloWorld
{ public static void main(String[] args)
{
NotHelloWorldFrame frame =
new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
COMP201 Topic 11 / Slide 7
Introduction/First Applet
Applets are created, run, and destroyed by web browser
Don’t set size for an applet: determined by HTML file.
Don’t set title for an applet: applets cannot have title bars.
No need to explicitly construct an applet. Construction code placed
inside the init method.
There is no main method.
An applet cannot be closed. It terminates automatically when the
browser exit.
No need to call method show. An applet is displayed automatically.
COMP201 Topic 11 / Slide 8
Introduction/Running An Applet
1.
Compile the .java file
2. Create a HTML file that tells the browser which file to load and how to
size the applet
<html><body> This is an example.
<applet code=“NotHelloWorldApplet.class” width=300
height=300>
This text shown if browser doesn’t do Java.
</applet>
</body></html>
3.
View the HTML file with a browser or the command appletviewer
(for testing).
This works for applets extending Applet, but doesn’t work for those
that extend JApplet
COMP201 Topic 11 / Slide 9
Introduction/Running An Applet
Browser retrieves class file and automatically runs it
using its JVM.
Problem: JVM of browsers does not support newest
versions of Java (i.e. IDK 1.2 JDK 1.3)
Sun’s solution: require users to install the latest Java
plug-in.
(see http://java.sun.com/products/plugin/index.html)
COMP201 Topic 11 / Slide 10
Introduction/Running An Applet
Special HMTL tags needed for running applets with Java plug-in.
The use of those special tags is not straightforward.
Solution:
1.
Write HTML file using traditional tags
2.
Feeds it to HTML converter to produces a new HTML file with
the special tags.
3.
View the new HTML file.
Get the HMTL converter from course page (Online resources).
Example of HTML file produced by converter
(NotHelloWordApplet.html)
COMP201 Topic 11 / Slide 11
Applet Basics/Class Loader and JAR Files
In the previous example, we have one classes
NotHelloWorldApplet.class,
Name of the applet class is placed in HTML file
Class loader first fetches NotHelloWorldApplet.class
In the process, if the class loader notices that some other
classes are also needed. It then makes another net connection
to get them.
Many connections might be needed in general, especially when
there are associated resources such as images and sounds.
Java Archive (JAR) files allow one to bundle a set of classes
and resources into one file that can be downloaded via one net
connection.
COMP201 Topic 11 / Slide 12
Applet Basics/Class Loader and JAR Files
Create JAR file with command jar
jar cf myJarFile.jar
*.class *.gif
pack all files ending with .class or .gif
Refer to JAR files in the APPLET tag
<applet archive=“myJarFile.jar”
code=“MyApplet.class”” width=300 height=300>
(see TetrixAppletJar.html and run TetrixAppletJar)
JAR file is downloaded via one net connection.
Class loader tries to find necessary files in JAR file before attempting
to get them from the net.
COMP201 Topic 11 / Slide 13
Diversion/Self-Running Jar File
“jar cfm …” creates a jar file and a manifest file
./META_INF/MANIFEST.MF
It describes features of the archive.
To make an executable jar file, we need to indicate the main class in
the manifest file.
Make mainclass.txt with one line (no “class” and ended by “return”)
Main-Class: MyApplet
Update the manifest variable
jar umf mainclass.txt MyJarFile.jar
Run:
java -jar MyJarFile.jar
Or click on file icon
Self-Running Tetrix Jar
COMP201 Topic 11 / Slide 14
Applet Basics/Security
Applets are downloaded from the net and executed
by a browser’s JVM immediately.
User never gets a chance to confirm or to stop an
applet from running.
Consequently, applets are restricted in what they can
do.
The applet security manager is responsible for
enforcing access rules and throws an
SecurityException when an access rule is
violated.
COMP201 Topic 11 / Slide 15
Applet Basics/Security
By default, an applet is restricted to run “inside the
sandbox”. Strictest security restrictions.
Signed applets can have more access privileges.
For now, we consider only applets playing in the
sandbox.
Access rights for Applets and Java Applications (JA)
BR: applets running inside a browser with default applet
security model
AV: applets running insider Applet viewer
BR
AV
JA
Read local file
N
Y
Y
Write local file
N
Y
Y
Get file info.
N
Y
Y
Delete file
N
N
Y
Run another program
N
Y
Y
Read the user.name property
N
Y
Y
Y
Y
Y
N
Y
Y
Load Java library
N
Y
Y
Call exit
N
Y
Y
warning
Y
Y
Connect to network port on home server
Connect to network port on other server
Create a pop-up window
COMP201 Topic 11 / Slide 17
Applet Basics/Applet Life Cycle
•
An application starts from main and runs until exit
Applets are controlled by browser
–
–
–
–
•
Born when their pages are first loaded
Respond to messages and user inputs when visible
“Turned off” when not visible
Disposed by browser either when changing page or quitting
Change behavior by overriding methods:
–
init(); start(), stop() & destroyed()
All those methods are called automatically
COMP201 Topic 11 / Slide 18
Applet Basics/Applet Life Cycle
public void init()
–
–
One-time initialization when first loaded
Good place to process parameters and add interface
components.
• public void start()
–
–
–
Called whenever user returns to the page containing
the applet after having gone off to other pages.
Can be called multiple times.
Good place to resume animation or game
COMP201 Topic 11 / Slide 19
Applet Basics/Applet Life Cycle
public void stop()
–
–
Called when user moves off page
Good place to stop time-consuming activities such as
animation and audio playing.
• public void destroy()
–
–
–
Called when browser shuts down.
Good place to reclaim non-memory-dependent
resources such as graphics contexts.
Normally, no need to worry.
COMP201 Topic 11 / Slide 20
Converting Applications to Applets
Java applications can easily to converted into applets
Non-IO codes stay essentially the same.
Inputs from home server are easy to handle.
Outputs to home server are more advanced (CGI, Servlet).
(Applets cannot communicate with other servers. “Applets can
only phone home”. If applets are to communicate with other
servers, including the local server, more access rights have to
be given using a security policy file.)
Non-IO applications first.
1.
Pop up a window for application
2.
Place top-level frame of application inside a browser
COMP201 Topic 11 / Slide 21
Converting Applications to Applets
Popping up a window for application.
What to do:
Assume: Separate class for creating and showing a toplevel frame. (If this class also does some other things, move
the other things to other classes.)
class NotHelloWorldFrame extends JFrame {…}
public class NotHelloWorld
{ public static void main(String[] args)
{ JFrame frame = new NotHelloWorldFrame();
frame.show();
}
}
COMP201 Topic 11 / Slide 22
Converting Applications to Popup
Applets
Delete the class for creating and showing the toplevel frame
Add an applet class whose init method contains
the same instructions as main method of deleted
class.
public class NHWApplet extends JApplet
{ public void init()
{
JFrame frame = new NotHelloWorldFrame();
frame.show();
}
} //NHWApplet.class
The popup window coming with a warning message
for security reasons, (which can be avoided for
signed applets).
COMP201 Topic 11 / Slide 23
Converting Applications to
embedded Applets
Placing top-level frame of application inside browser.
What to do: (Assume: main is in the definition of the top-level frame &
its only purpose is to create a window and show it.
NotHelloWorld.java)
• JFrame class => JApplet class; must be public
• Remove setSize: set in HTML file
• Remove addWindowListener: Applet cannot be
closed
• Remove setTitle: Applet cannot have title bar
• Replace constructor with init.
• Delete the main method.
COMP201 Topic 11 / Slide 24
Converting Applications to
embedded Applets
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{
setTitle("NotHelloWorld");
setSize(300, 200);
Container contentPane = getContentPane();
contentPane.add(new NotHelloWorldPanel());
}
}
public class NotHelloWorld
{ public static void main(String[] args)
{
NotHelloWorldFrame frame =
new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
COMP201 Topic 11 / Slide 25
Converting Applications to Applets
public class NotHelloWorldApplet extends JApplet
{ public void init()
{
Container contentPane = getContentPane();
JLabel label = new JLabel("Not a Hello,
World applet", SwingConstants.CENTER);
contentPane.add(label);
}
} //NotHelloWorldApplet.java
COMP201 Topic 11 / Slide 26
Resources for Applets
One can provide information to applets in HTML file
Applets can access resources at home server:
Text
Multimedia
COMP201 Topic 11 / Slide 27
Passing Info to Applets via HTML File
In HTML file, use PARAM, NAME, VALUE tags
<APPLET CODE="Chart.class" WIDTH=400 HEIGHT=300>
<PARAM NAME="title" VALUE="Diameters of the Planets">
<PARAM NAME="values" VALUE="9">
…. </Applet>
In applet, use the getParameter method of the Applet class
getParameter("title"); // returns "Diameters of the Planets“
String vString = getParameter(“values”); // returns “9”
if (vString == null )
{do something}
// precaution
else
int v=Integer.parseInt(vString);//must parse to get numbers
Chart.java, Chart.html
COMP201 Topic 11 / Slide 28
Accessing Resources at Home Server
Where is home?
Inside a subclass of Applet
Inside any other class x
getDocumentBase returns URL of the html file that calls the
applet
getCodeBase returns URL of the applet itself
x.class gives one an object of the Class class that contain
information of x.
(Class is a special class and has method getResource.
C.f. Object class)
x.class.getResource( resourceName ) returns URL
of resource
Need the URL class in java.net package
import java.net.*
COMP201 Topic 11 / Slide 29
Accessing Text Files at Home Server
Find the URL of text file and the create an InputStream using
the openStream method of URL class
InputStream in = url.openStream();
Or create an InputStream directly using the
getResourceAsStream method of the Class class.
InputStream in = x.class.getResoruceAsStream(
fileName);
The InputStream can be nested with other streams in the
normal way (see Topic 4)
ResourceTest.java, ResourceTest.html
COMP201 Topic 11 / Slide 30
Accessing Images at Home Server
Applets can handle images in GIF or JPEG format
Load images
Inside an subclass Applet, use
getImage(url), getImage(url, name)
Inside other classes java.awt.Toolkit
Toolkit.getDefaultToolkit().getImage( url );
How to show an image?
ImageLoadApplet.java
Exercise: Load the images in applet class
COMP201 Topic 11 / Slide 31
Accessing Audio Files at Home Server
Applets can handle audio files in AU, AIFF, WAV, or
MIDI format.
Audio Clips (java.applet.Applet)
Load:
AudioClip getAudioClip(url),
AudioClip getAudioClip(url, name)
Then use play method of AudioClip to play
and the stop method to stop
Play without first loading:
void play(url),
void play(url, name)
//SoundApplet.java
COMP201 Topic 11 / Slide 32
Communication with Browser
To establish a communication channel between an applet and
browser, use the getAppletContext method of the Applet
class
The method returns an object of the AppletContext, which is
an interface.
Two useful methods of interface AppletContext
showDocument( URL url )
showDocument(URL url, String target )
ShowPageApplet.java
COMP201 Topic 11 / Slide 33
Weird Trick:
To avoid the additional HTML file, one can add an applet tag as
a comment inside the source file.
/*
<APPLET CODE = “MyApplet.class” WIDTH=300 HEIGHT=300>
</APPLET>
*/
public class MyApplet extends Japplet
…
Then run the applet viewer with the source file as its command line
arguments:
Appletviewer MyApplet.java
Not necessarily recommending this as standard practice. But it is
handy during testing.