java.awt and java.applet Packages
Original design goals:
- Simple GUI which looks good on all platforms.
- Use native peer classes to speed implementation time.
Problems with the AWT:
- Lowest common denominator controls only.
- Display varies by platform.
- Programming paradigm is not O-O.
- Difficult to implement inside a GUI builder.
Applet Introduction
What is an applet?
- Mini-application designed to be downloaded over the web and
run in a browser.
- Applet class provides a framework for programming applets.
- Applet differs from a normal application in the following
ways:
- An applet does not have a main() method.
- An applet is not invoked from the command line; it is
embedded within an HTML file with an APPLET tag.
- It is subject to a number of security restrictions designed
to protect against malicious code.
- Problems with applets:
- Security restricts you to a "sandbox".
- Can overcome security restrictions through digital signing.
- However, unsigned applets can only access network connections and
files on the web server from which they were loaded.
Life cycle of the applet:
- Loading the applet
- An instance of the applet's controlling class is created.
- The applet initializes itself (init called).
- The applet starts running (start called).
Standard applet methods to override:
- init() - Called when the applet is first loaded into
the browser or viewer. Used to perform applet initialization and
to construct its GUI components.
- start() - Called when the applet becomes visible and should
start doing whatever it is that it does. An applet that performs
animation or does some other action only when it is visible needs to
implement this method.
- stop() - Called when th applet becomes temporarily invisible
(e.g., when the user has scrolled it off the screen). Tells the applet
to stop performaing an animation or task.
- destroy() - Called when the applet is about to be unloaded from
the browser or viewer. The method should free any resources, other
than memory that the applet has allocated.
- getAppletInfo() - Called to get information about the applet
(e.g., its name and author). This method should return a string
suitable for dispay in a dialog box.
- getParameterInfo() - Called to obtain information about
the parameters to which the applet responds. Returns a String[][] that
describes the paramters.
See the Simple.java applet
for an illustration of the applet life cycle.
Other applet methods to invoke:
- getImage() - Loads an image from the network and returns
an Image object.
- getAudioClip() - Loads a sound clip from the network and
returns an AudioClip object.
- getParamter() - Looks up and returns the value of a
named parameter, specified with a tag in the HTML file
that contains the applet.
- getCodeBase() - Returns the base URL from which the
applet class file was loaded.
- getDocumentBase() - Returns the base URL of the HTML file
that refers to the applet.
- showStatus() - Displays a message in the status ine of the
browser or applet viewer.
- getAppletContext() - Returns the AppletContext object for
the applet. This context defines the useful showDocument() method
that asks the browser to load and dipslay a new web page.
Applet Tag
- <APPLET>
- Specifies an applet to run within a web document. A browser that
does not support applets displays the alternate text.
- <CODE>
- Required. It specifies the name of the class file that contains
the compiled Java code. It must be relative to the code base. May
be replaced by the OBJECT attribute under JDK 1.1.
- <WIDTH>
- Required. Initial width in pixels of the applet in the browser
window.
- <HEIGHT>
- Required. Initial height in pixels of the applet in the
browser window.
- <OBJECT>
- As of JDK 1.1, specifies the name of a file containing a serialized
applet. Note that the "init" method of the applet is called. Thus,
the applet should be initialized but not started before it is serialized.
- <ARCHIVE>
- Optional. As of JDK 1.1, a comma-separated list of JAR files to be loaded.
These files may contain class files, images, sound files, etc. Note
that the local disk is searched first.
- <CODEBASE>
- Optional. Base URL (absolute or relative) of the applet to be
displayed. If not specified, the document base is used.
- <ALT>
- Optional. Text to be displayed for browsers that do not
understand applets.
- <NAME>
- Optional. Assigns a name to an applet. Can be used by other
applets for communication purposes.
- <VSPACE>
- Optional. Margin in pixels to be placed at the top and bottom
of the applet.
- <HSPACE>
- Optional. Margin in pixels to be placed at the left and right of
the applet.
- <PARAM NAME="x...x" VALUE="x...x">
- Optional. Used to pass parameters to the applet. The getParameter() method specifies the name and receives the value.
Applet Packaging
Applets should be packaged using jar files:
- Makes it less likely that any class files are "lost".
- Improved performance since load time reduced.
In order to get the features of Java 1.2, you must use the Java Plug-in:
- Works only under Windows and Solaris.
- Actual plug-in under Netscape.
- ActiveX control under IE.
- Uses the OBJECT rather than the APPLET tag under IE and
EMBED tag under Netscape. Sun provides a tool
to convert applet tags to the correct format.
- May be slow to download the first time over a dial-up connection.
Sample plug-in tag:
Original APPLET tag:
<APPLET code="MessageApplet.class" width=350 height=125>
<PARAM name="message" value=Hello World">
</APPLET>
After conversion for Plug-in:
<OBJECT classid="clsid:8AD9C840-044E-11D1-BE39-00805F499D93"
codebase=
"http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab#Version=1,2,0,0"
WIDTH=350 HEIGHT=125>
<PARAM NAME=CODE VALUE="MessgeApplet.class">
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.2">
<PARAM NAME="message" VALUE="Hello World">
<COMMENT>
<EMBED type="application/x-java-applet;verion=1.2">
pluginspage=
"http://java.sun.com/products/plugin/1.2/plugin-install.html"
java_CODE="MessageApplet.class"
WIDTH=350 HEIGHT=125 message="Hello World">
</EMBED>
</COMMENT>
</OBJECT>
Applet Security
- Untrusted applets cannot read or write to the local file system; i.e.,
they cannot:
- Untrusted applets cannot perform network operations except in
very restricted ways. In particular, they cannot:
- Create a network connection to any computer except the one from
which the code was loaded.
- Listen for network connections on any port equal to or below 1024.
- Use Multicast sockets.
- Create or register a SocketImplFactory, URLStreamHandlerFactory
or a ContentHandlerFactory.
- Untrusted applets may not use certain system facilities; they may not:
- Exit by calling "System.exit()" or "Runtime.exit()".
- Spawn new processes by calling "Runtime.exec()".
- Dynamically load native code libraries.
- Untrusted applets cannot use certain AWT facilities:
- Initiate a print job.
- Access the system clipboard.
- Acess the system event queue.
- All secondary windows display a prominent warning that the
code may be insecure.
- Untrusted code has restricted access to system properties. It cannot
call "getProperites()"; however, it can call "getProperty()" to get
individual properties to which it has been granted access.
- Untrusted applets cannot create or access threads or thread
groups outside the thread group in which it is running.
- Untrusted applet have restrictions on the classes the can load
and define; they cannot:
- Explicitly load classes from the sun.* packages.
- Define classes in any of the java.* or sun.* packages.
- Create a Classloader object or call any Classloader
methods.
- Untrusted applets cannot use the java.lang.Class reflection
method to obtain information about nonpublic members of a class unless
the class was loaded from the same host as the untrusted code.
- Untrusted applets have only limited use of the java.security
package; they cannot:
- Manipulate security identities in any way.
- Set or read security properties.
- List, look up or insert security providers.
- Create or register a SecurityManager object.
In order to overcome the security restrictions, you must sign your applet:
- Need a digital certificate from someone like Verisign.
- Use an appropriate signing tool:
- JDK 1.1 - javakey
- JDK 1.2 - jarsigner
- Netscape - signtool; must also use capability classes.
- IE - ?
AWT Programming
Drawing applications:
- Use a Canvas component.
- Use the methods of the Graphics class to:
- Draw lines, rectangles, ovals, etc.
- Display text.
- Great things using the Java2D API.
- Use the Image class to load and animate images.
Form/data entry applications:
- Use Panels to contain components.
- Use any of the following:
- Button - push button.
- Label - Display-only text.
- TextField - single line entry field.
- TextArea - multi-line entry field.
- Choice - drop down list.
- CheckBox - check boxes and radio buttons.
- List - list with scrollbars.
See the Components.java
program for an example of all of the
components listed.
Components should always be positioned using a
LayoutManager and
not absolute positioning.
Adding a Menu to an Application
Classes involved:
- Menubar - Platform-specific menubar. Use setMenubar()
method of the Frame to associate the frame with the menu bar.
- Menu - A drop down menu.
- MenuItem - Each item in the menu.
- CheckboxMenuItem - A menu item which contains a checkbox.
- PopupMenu - popup menu.
Adding a menu to an application:
- Create a menubar item:
MenuBar mb = new MenuBar();
- Associate the menubar with frame:
setMenuBar(mb);
- Create the dropdown menus:
Menu menu1 = new Menu();
- Add the menu items to the menu and optionally define shortcut keys.
MenuItem mi = new MenuItem("File");
mi.setShortcut(new MenuShortcut(KeyEvent.VK_F2));
menu1.add(mi);
- Add an action listener to each menu item.
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
...
}
});
- Add menu separators if needed:
menu1.addSeparator();
- Repeat for all additional items.
- Optionally, define one of the menus to be the help menu. On some
platforms, this positions this on the far right:
mb.setHelpMenu(menu);
Creating a popup menu:
- Create the popup menu and add it to the container.
Popup popup = new PopupMenu("Popup Menu");
add(popup);
- Create the menu items and add them to the popup just
as for the regular menu.
MenuItem mi = new MenuItem("File");
popup.add(mi);
- Define a mouse listener to handle the display of the popup
menu when the appropriate mouse button is clicked. Note that some
platforms use "mouse pressed" and others use "mouse released".
class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
- Instantiate the popup mouse listener and add it to the container.
MouseListener listener = new PopupListener();
addMouseListener(listener);
Converting an Applet to an Application
In order to convert an applet to an application, do the following:
- Add a main method.
- In main create a Frame to hold the applet.
- Instantiate the applet and add it to the center of the frame.
- Invoke the init and start methods.
- Handle the window closing event on the Frame; also invoke the
stop and destroy methods, if necessary.
Reading Assignment
- Chapter 9, 11 and 13 of Java Certification Handbook
- Chapter 13 of Thinking in Java
Programming Assignments:
- Work on your Palarco project.