Chapter 4 - Applets : Programming for the World Wide Web
|
Chapter Objectives:
-
Be able to design and implement a Java applet.
-
Understand Java's event handling model.
-
Be able to handle button clicks in your programs.
-
Have a better appreciation of inheritance and polymorphism.
-
Know how to design a simple Graphical User Interface (GUI).
|
Index:
|
Introduction
-
An applet is a Java program embedded within a Web page and run by
a Web browser.
-
An applet has a graphical user interface (GUI ).
-
Java applet programming is event-driven programming.
-
Applets are much like java applications with the following exceptions:
-
You use the Applet
class instead of the JFrame class to build your application.
-
Like JFrame, Applet already has a content pane with a default FlowLayout,
you may set its layout manager
-
There is no "main" method. Instead, a method called init() is called
first.
-
init() is where you should add the code to build and initialize the content
pane.
-
You don't have to setup the size of the applet in the java code, instead,
this is done in the HTML code.
-
Currently many browsers don't support version 2 of Java and/or they
don't have the swing classes in their code libraries. Therefore its best
to stick with Java version 1 conventions. Before you use a class check
the help file for the class and see when it originated. If it says "Since
1.0" then you are ok. To be safe don't use any Swing classes (JApplet,
JButton, JTextField, i.e. all the J... classes) instead use the AWT classes
(Applet, Button, TextField, Label, etc). There is a way to make it work
(by adding in a Java plug-in to the browser, running JAVA as a plugin is
the future). Not all browsers support all functions. For example, Netscape
version 4.76 does not support the getImage routine (used in chapter 8).
-
After learning the Swing classes (JLabel, JButton, etc.) you will be a
little disappointed with the AWT versions of the same items. For example,
the buttons don't support icons and tool tip text.
Figure 4-2 Java's AWT Objects often used in Applets
Figure 4-7 Sample Hierarchy for SimpleApplet Example
Example : SimpleApplet
-
This applet mere displays a button that changes each time you press it.
-
Code for this applet:
/*
* File: SimpleApplet.java
* Author: Java, Java, Java
* Description: This program illustrates the basic
* format for a Java applet. The SimpleApplet class
* extends the Applet class and implements the ActionListener
* interface. The applet's execution begins in the init()
* method, which is called automatically by the browser.
It
* initialized the applet. The actionPeformed() method is
* called automatically whenever the user clicks on the
toggle
* button. Each time the button is clicked, it changes its
* label. Clicking a button is an example of a "action event",
* which is handled by the actionPerformed() method.
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleApplet extends Applet implements ActionListener
{
private Button toggle;
// From java.awt.Button
/*
* The init() method instantiates the toggle Button,
assigns
* it an ActionListener, and adds it to the applet.
This causes
* the button to appear on the applet's window.
*/
public void init()
{
toggle = new Button ("The
machine is off");
toggle.addActionListener(this);
add(toggle);
} // init()
/*
* The actionPerformed() method is called whenever
the toggle
* button is clicked. It reverses the button's
label.
*/
public void actionPerformed(ActionEvent e)
{
String str = toggle.getLabel();
// Get the toggle Button's label
if (str.equals("The machine
is on")) // and change
it
toggle.setLabel("The machine is off");
else
// or
toggle.setLabel("The machine is on"); // change it back
} // actionPerformed()
} // SimpleApplet
Due to security Applets can't:
-
read or write files on the user's system
-
communicate with an internet site other than the one they originated on
-
run or load any programs in the user's system
-
You can read files from the server where the applet resides and communicate
with that server
Other programming notes:
-
you can add any of the following methods to control interaction if needed:
-
start() - this is called whenever the applet begins (after the init) and
whenever the user leaves the applet page, then returns to it in the browser
-
stop() - called whenever a user leaves the applet page
-
destroy() - allows the applet to perform cleanup before it is released
from memory
-
paint() is called whenever the applet needs to repaint itself, this occurs
if the browser is minimized then restored, during scrolling and any other
time the applet becomes visible. NOTE: you only have to provide a paint
method if you are doing graphics with a Canvas or Graphics2D object. Buttons,
lists, etc repaint themselves.
-
If you rebuild your applet you will probably have to exit the browser
then restart it to get the new version loaded. Pressing the reload button
on the browser may not due the trick.
-
Java Console
-
Java Console is a window built into most browsers that display error messages
from applets and allow a very limited amount of debugging of applets.
-
You can use the java console like you did the dos window for displaying
debugging messages.
-
In Netscape the java console is found under menu item Communicator-Tools-Java
Console.
-
Internet Explorer hides the java console, to access it you first
must turn it on. To do this
-
Start IE
-
Select Tools-Internet Options
-
Click on the Advanced tab
-
Scroll down until you see the checkbox labled "java console enabled", turn
that on
-
exit IE
-
restart IE (just IE not your computer)
-
You now may access the Java Console, Select View-Java Console from
the menu.
-
To display a message in the console use the System.out.println method,
since there is no DOS window, the messages will go to the JAVA Console
The Applet HTML Tag
-
Creating the HTML to show the applet.
-
You should use the Applet (the newer Object tag can be used as well)
<applet
CODE = "Calculator.class"
ARCHIVE = "Calculator.jar"
WIDTH = 200
HEIGHT = 200
HSPACE = 0
VSPACE = 0
ALIGN = Middle> </applet>
-
The CODE parameter identifies the name of the Applet class
-
The Archive parameter identifies the name of a JAR file that holds all
the class files, gifs, and jpgs associated with the applet. This parameter
is omitted if you do not create a jar file. Instead, be sure to have all
the class files in the same directory as the one specified in the code
parameter.
-
The Width and Height specifiy how big a space on the web page to allocate
for the applet. this is in pixels
-
the HSPACE and VSPACE specify the amount of space around the applet to
separate from text on the web page
-
the Align positions the applet window on the web page. This works much
the same way as aligning text and images on a web page.
JAR Files
-
Creating JAR files
-
If you applet requires more than one class file, or has jpg, wav, gifs,
or other files associated with it, then you should create a JAR file.
-
A JAR file takes all the files needed for an applet and zips them together
into one file. This makes managing the files on the web site easier and
downloading by clients faster.
-
To create a JAR file, use the JAR utility (included with the JAVA SDK).
For the Calculator Applet:
-
jar cf Calculater.jar *.class
-
jar cf Calculator.jar Calculator.class KeyPad.class
-
The c in the cf tells jar to create a new file. The f
says that you will specify the name of that file.
-
JAR files can also be used for applications to make them run like
.EXE files.
Calculator Applet
Click here to see the code
WebMenu Example
-
This applet shows a couple of new things: how to put messages on the browser
status line, and how an applet can interact with the browser.
-
To display a message in the status line of the browser use the showStatus
method of the Applet.
showStatus("the message");
-
Loading Web pages. For an applet to tell the browser
to go to a different page you must first create a URL object then use the
showDocument method of the AppletContext.
try{
URL link = new URL(links[index]);
getAppletContext().showDocument(link);
// link is a string that has the URL
}
catch(MalformedURLException
ex) {
showStatus("Bad URL:"+links[index]);
}
-
optionally the showDocument method can take a second parameter that specifies
where to show the document (similar to the target parameter on an HTML
a href tag). e.g.
getAppletContext().showDocument(link,"_blank");
// show the document in a new browser window.
-
"_self" Show in the window and frame that contain
the applet.
-
"_parent" Show in the applet's parent frame. If the applet's
frame has no parent frame, acts the same as "_self".
-
"_top" Show in the top-level frame of the applet's window.
If the applet's frame is the top-level frame, acts the same
as "_self".
-
"_blank" Show in a new, unnamed top-level window.
-
name Show in the frame or window named name.
If a target named name does not already exist, a new top-level window
with the specified name is created, and the document is shown there.
Click here to see WebMenu Applet Code
Example: An Applet that Sketches
-
This program provides basic sketching features for a web page. It consists
of two classes:
-
Sample12 - is the applet that provides the structure using a border layout.
on the west is a tool bar built from a panel with a number of color buttons.
on the south is a status line showing the current color, and in the center
is a Sketch object.
-
Sketcher - is a class that provides a surface (Panel) to draw on and
handles input from the mouse. When the mouse is moved across the surface
with the button down then a line appears in the current color. Sketcher
inherits/extends Panel and implements MouseListener (for button clicks)
and MouseMotionListener (for mouse move events). Chapter 10 talks more
about JAVA graphics functions.
-
New things:
-
MouseListener - this was implemented in the Sketcher class. The
constructor for Sketcher add an action listener for the MouseListener.
The MouseListener events let Sketcher know when a button was pressed, when
it was released, and when the mouse entered and exited the Sketcher's boundaries.
-
MouseMotionListener this was implemented in the Sketcher class.
The constructor for Sketcher add an action listener for the MouseMotionListener.
The MouseMotionListener events let Sketcher know when the mouse moved (with
or without a button down).
-
MouseEvent - this object is generated and sent to the listeners.
It contains methods to determine the x,y location of the mouse at the time
of the event and the state of the mouse buttons.
-
Graphics class - Sketcher creates a graphics class whenever it needs
to draw something on the screen. Graphics class provides many functions
to draw shapes, lines, and text. In this case I used the setColor
and drawLine functions.
-
Other notes:
-
What's missing from this graphics application ??
-
Answer - a paint function. Sketch something on the applet,
then minimize and restore your browser. The picture will be gone.
This is because there is no automatic way for JAVA to know what to restore
to the drawing area. You have to provide a paint method (in this case added
to the Sketcher class), and enough intelligence to recreate what was drawn.
To implement painting the sketcher should maintain a vector containing
objects that represent line segments. Each line segment would have an x,y
points for the start and end points and the color. Each time a mouse event
draws another line segment it should create a line segment object and add
it to the vector. Then when paint is called, the vector can be traversed
and all the line segments redrawn.
click here to see the code for the sketching applet
Example: CyberPet Applet
-
Class Name: CyberPetApplet
-
Task: User interface for the CyberPet simulation.
-
Information (instance variables)
-
pet: A reference to a CyberPet
-
nameLabel: A Label for the pet's name.
-
stateField: A TextField for the pet's state.
-
eatButton: A Button for the eat command.
-
sleepButton: A Button for the sleep command.
-
Manipulations Needed (public methods)
-
init(): Creates the GUI components and initialize.
-
actionPerformed(): Handles clicks on the Buttons
click here for the CyberPet code
Future of Applets
-
Due to the ongoing battles between Sun and Microsoft support for JAVA applets
from browsers is in question. Rumors have it that Microsoft XP will ship
without a Java Virtual Machine (you can still install one from Sun, that's
your best bet in any case).
-
The best way around this is to run your applets as plugins. That way you
do not have to worry about what version of what browser will be used, and
you can use the full power of JAVA 2 and Swing's JApplet class.
-
Java Plug-in software enables enterprise customers to direct applets or
JavaBeansTM on their intranet web pages to run using Sun's Java 2 Runtime
Environment, Standard Edition (JRE) instead of the web browser's default
virtual machine. Sun's JRE provides a Java CompatibleTM environment
for today's widely adopted web browsers. That means consistency and
reliability when running applets.
-
In order to use the plugin the end user must have the plugin installed
and the web page containing the applet must have HTML code that directs
the plugin to run the applet.
-
Sun provides an HTML converter that will change your APPLET tags to code
that can check for and launch the Plugin.
-
Click
here for information on how to do this.
Summary
Keywords:
abstract class, abstract method, applet,Application Programming Interface
(API), event-driven, Graphical User Interface (GUI), inheritance, inheritance
hierarchy, interface, polymorphism
Suggested Exercises : 1, 2, 4, 5, 6, 12, 17, 18