CS 596 Java Programming Fall Semester, 1998 Applets |
||
---|---|---|
© 1998, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 21-Dec-98 |
First Applet
The HTML <HTML> <HEAD> <TITLE>HelloApplet</TITLE> </HEAD> <BODY> <HR> This is the first Applet<P> <APPLET code="HelloApplet.class" width=100 height=100> </APPLET><BR> The End <HR> </BODY> </HTML>
The Java Code import java.awt.*; import java.applet.Applet; public class HelloApplet extends Applet { public void init() { repaint(); } public void paint( Graphics g ) { g.drawString( "Hello World!", 30, 30 ); } }
Output Note: all examples are done using the applet viewer
Running the Example - AppletViewer
The good way to view and debug applets is with the appletviewer. See http://www.sdsu.edu/doc/jdk1.1/docs/tooldocs/solaris/appletview.html or http://www.eli.sdsu.edu/doc/jdk1.2/tooldocs/solaris/appletviewer.html for information about using the appletviewer. The documentation at http://java.sun.com/products/jdk1.2/docs/tooldocs/solaris/appletviewer.html has more information.
appletviewer URLOfTheHTMLFile
will display applet referred to in the HTML.
Running the Example - BrowserFile You can use the open file menu item on either Internet Explorer or Netscape's browser (Navigator or Communicator) to open the html file. This will display both the html and the applet. Note that when loaded in a browser, you have to quit then restart the browser to reload browser.
From Web Server You can also load the applet from a web server. See http://www-rohan.sdsu.edu/pagecreate.html for instructions on how to publish a web page on rohan. Once you have made the html file that refers to the applet available, just access the page via a Java enabled browser.
Classpath and Applets When you run an Applet in a browser, the browser uses its own version of Java. The browser does not use your classpath. This means you must make sure that all the classes used by your applet are either in the JDK supported by the browser, or downloaded with the applet. For security reasons an applet can not download classes in the java.* packages. In JDK 1.0 and 1.1, the appletviewer did use your classpath. This means that an applet using classes in your classpath would work when tested in the appletviewer but not in a browser. The appletviewer with the JDK 1.2 FCS (FCS = first customer ship, Sun's way of telling specifying an actual release from a beta) does not use your classpath.
Applets & Browsers on Rohan As of December 6, 1998, none of the versions of Netscape's browsers on rohan are fully complaint with JDK 1.1.
Applet Tags
See: http://java.sun.com/products/jdk/1.2/docs/tooldocs/appletviewertags.html for more information about the tags supported by the appletviewer.applet The applet tag is the original HTML 3.2 tag for embedding an applet in an HTML page
<APPLET ARCHIVE="yourJar1.jar" CODE="yourClass.class" OBJECT="serializedObjectOrJavaBean" CODEBASE="classFileDirectory" WIDTH="pixelWidth" HEIGHT="pixelHeight" NAME="appletName" HSPACE="n", VSPACE="n" ALIGN=left | right | top | middle | bottom > <PARAM NAME="..." VALUE="..."> ... alternate-text </APPLET>
Only one of CODE or OBJECT is specified. The optional CODEBASE attribute supplies a relative URL that specifies the location of the applet class. The optional ARCHIVE indicated a jar file(s) search for files. PARAM tags supply argument values for applet parameters. HSPACE and VSPACE control horizontal and vertical spacing around the applet. We will see examples of these options later.
object
The object tag is the HTML 4.0 tag for embedding applets and multi-media objects into an HTML page. In HTML 4.0, the applet tag is deprecated. The object tag is also an Internet Explorer 4.x extension to HTML 3.2 which allows IE to run a Java applet using the latest Java plug-in from Sun. The object tag is the HTML 4.0 tag for embedding applets and multi-media objects into an HTML page. It is also an Internet Explorer 4.x extension to HTML 3.2 which allows IE to run a Java applet using the latest Java plug-in from Sun. Later we will cover more about this tag and the plug-in.
<OBJECT WIDTH="pixelWidth" HEIGHT="pixelHeight" > <PARAM NAME="code" VALUE="yourClass.class"> <PARAM NAME="object" VALUE="serializedObjectOrJavaBean"> <PARAM NAME="codebase" VALUE="classFileDirectory"> ... alternate-text </OBJECT>
embed
The embed tag is the Netscape extension to HTML 3.2 that allows embedding an applet or a multimedia object in an HTML page. It allows a Netscape 4.x browser (which supports HTML 3.2) to run a Java applet using the latest Java plug-in from Sun. Later we will cover more about this tag and the plug-in.
<EMBED CODE="yourClass.class" OBJECT="serializedObjectOrJavaBean" CODEBASE="classFileDirectory" WIDTH="pixelWidth" HEIGHT="pixelHeight" > ... </EMBED>
Applet Methods
destroy()
getAppletContext()
getAppletInfo()
getAudioClip(URL)
getAudioClip(URL, String)
getCodeBase()
getDocumentBase()
getImage(URL)
getImage(URL, String)
getLocale()
getParameter(String)
getParameterInfo()
init()
isActive()
play(URL)
play(URL, String)
resize(Dimension)
resize(int, int)
setStub(AppletStub)
showStatus(String)
start()
stop()
init()
Basic Methods Example
This example just displays when the basic applet methods are run in an applet. The output is displayed in a TextArea. In order to save space on the slide, I will only display the applet part of the HTML. This does work with the applet viewer and broswers, although it is not proper HTML.
HTML <APPLET CODE="BasicEventApplet.class" WIDTH=300 HEIGHT=200> </APPLET>Java Code import java.awt.*; import java.applet.Applet; public class BasicEventApplet extends Applet { TextArea messages = new TextArea(8, 30); public BasicEventApplet() { messages.append( "Constructor\n" ); } public void init() { add( messages ); messages.append( "Init\n" ); } public void start() { messages.append( "Start\n" ); } public void stop() { messages.append( "Stop\n" ); } public void destroy() { messages.append( "Destroy\n" ); } public void paint( Graphics g ) {messages.append( "Paint\n" ); } }
Output Note: all examples are done using the applet viewer
Alternative Text
Some browsers do not support applets. You should provide alternative text to be displayed in such browsers. The tag below provides such text.
<APPLET CODE="BasicEventApplet.class" WIDTH=300 HEIGHT=200> Your browser does <B>not</B> support applets! So you can not use my great applet. </APPLET>
Alignment There is some control over the alignment of the applet.
<APPLET CODE="BasicEventApplet.class" WIDTH=300 HEIGHT=200 ALIGN="right"> </APPLET>
left
Applet Parameters
This example shows how to pass information to an applet from the html page. The getParameter() method will read arguments with the param tag. It also seems to read the width & height. The methods getAppletInfo() & getParameterInfo() are used by the applet viewer to provide the user with information about the applet.
HTML <APPLET CODE="ParameterApplet.class" WIDTH=300 HEIGHT=200> <PARAM NAME="name" VALUE="Roger"> <PARAM NAME="yourHeight" VALUE="5"> </APPLET>Java Code import java.awt.*; import java.applet.Applet; public class ParameterApplet extends Applet { TextArea messages = new TextArea(8, 20); public void init() { add( messages ); String name = getParameter( "name" ); int height = Integer.valueOf (getParameter( "yourHeight" )).intValue(); messages.append( "name: " + name + "\n" ); messages.append( "height: " + height + "\n" ); } public String getAppletInfo() { return "This applet shows how to pass information" + " from the html document to the applet"; } public String[][] getParameterInfo() { return new String[][] { { "name" , "string", "your name" }, { "yourHeight", "int" , "your height"} }; } }
Output Note: all examples are done using the applet viewer
Multiple Files
An applet may require more than one .class file, or it may require a sound file or image files. By default, all files are loaded from the same location as the .html file that refers to the applet. In the following example, the applet requires the file AnotherClass.class to run. It is downloaded from the same location as the .html file and the MultipleFilesApplet.class file.
HTML <APPLET CODE="MultipleFilesApplet.class" WIDTH=300 HEIGHT=200> </APPLET>Java Code import java.awt.*; import java.applet.Applet; public class MultipleFilesApplet extends Applet { public void init() { repaint(); } public void paint( Graphics display ) { AnotherClass test = new AnotherClass(); display.drawString( test.name(), 20, 20 ); } } public class AnotherClass { public String name() { return "Roger"; } }
JAR Files
The files required by an applet can be placed into a jar file. A jar file is a compressed file (zip algorithm) with a manifest (list of contents). This can speed up the transfer of the applet in two ways. First, the file is compressed. Second, if requires only one interaction with the web server to obtain all the needed files. The example below, shows how create and access a jar file for the applet on the previous slide. The jar file can contain images and sound.
The basic syntax for creating a jar file is:
jar -cf jarFileName.jar file1, file2, ..., fileN
where file1, ..., fileN are the files to put into the jar file. See the java tool documentation for more information about the jar command. See for example: http://java.sun.com/products/jdk/1.2/docs/tooldocs/solaris/jar.html. The following command creates the file myJar.jar for the example on the previous slide.
jar -cf myJar.jar AnotherClass.class MultipleFilesApplet.class
The following applet tag tells the browser/appleviewer to also look into the jar file myjar.jar to find any files needed by the applet. The jar file will be loaded from the same location as the html file. You can specify more than one jar file by separating the file names with commas: archive="jar1.jar, jar2.jar".
<APPLET ARCHIVE="myJar.jar" CODE="MultipleFilesApplet.class" WIDTH=300 HEIGHT=200> </APPLET>
Size of Applet Area This example shows how to determine the applet's size.
HTML <APPLET archive="AppletClasses.jar" code="SizeApplet.class" width=100 height=100> </APPLET>Java Code import java.awt.*; import java.applet.Applet; public class SizeApplet extends Applet { public void init() { repaint(); } public void paint( Graphics display ) { Dimension size = getSize(); display.drawString( "height = " + size.height, 30, 30 ); display.drawString( "width = " + size.width, 30, 50 ); display.drawRect( 0, 0, size.width-1, size.height-1); } }Output Note: all examples are done using the applet viewer
CodeBase Use the codebase tag to specify a location to find the files needed by the applet. You can specify the location relative to the location of the referencing .html file (document base) or give a full URL.
Specify Full URL Look for the .class files in the specified location
<APPLET CODEBASE= "http://www.eli.sdsu.edu/courses/fall98/cs596/notes/code" CODE="MultipleFilesApplet.class" WIDTH=300 HEIGHT=200> </APPLET>
Relative Location Look for the .class files in the subdirectory "code" from the document base.
<APPLET CODEBASE= "code" CODE="MultipleFilesApplet.class" WIDTH=300 HEIGHT=200> </APPLET>
With jar File <APPLET CODEBASE= "code" ARCHIVE="myJar.jar" CODE="MultipleFilesApplet.class" WIDTH=300 HEIGHT=200> </APPLET>
Status Window
Some browsers have a "status window". In Netscape's browser, this is the status line at the bottom of the browser window. The showStatus() method places text in that window.
import java.awt.*; import java.applet.Applet; public class StatusApplet extends Applet { public void paint( Graphics display) { showStatus( "Hi mom" ); } }
Applets & AWT
An Applet is a subclass of Container and Panel. FlowLayout is the default layout manager for applets. We can add any AWT component to an applet we can add to a Panel. The example below shows adding buttons to an applet.
HTML <APPLET archive="AppletClasses.jar" code="ButtonApplet.class" width=100 height=100> <param name="name" value="Roger"> </APPLET>Java Code import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class ButtonApplet extends Applet { Button red = new Button( "Red" ); Button blue = new Button( "Blue" ); public void init( ) { add( red ); add( blue ); red.addActionListener( new ColorActionListener( Color.red) ); blue.addActionListener( new ColorActionListener( Color.blue) ); } class ColorActionListener implements ActionListener { Color backgroundColor; public ColorActionListener( Color aColor ) { backgroundColor = aColor; } public void actionPerformed( ActionEvent event ) { setBackground( backgroundColor ); repaint(); } } }
Output Note: all examples are done using the applet viewer
Applets and Windows
You can open windows in an applet. Depending on the browser and the security measures taken, the window usually marked as untrusted. The user may be asked if they will allow the applet to open the window.
HTML <APPLET archive="AppletClasses.jar" code="WindowApplet.class" width=100 height=100> </APPLET>Java Code import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class WindowApplet extends Applet { Button display = new Button( "Open" ); Frame buttonWindow = new ButtonExample( 75, 75 ); public void init( ) { add( display ); display.addActionListener( new DisplayListener( ) ); } class DisplayListener implements ActionListener { public void actionPerformed( ActionEvent event ) { if ( buttonWindow.isVisible() ) { display.setLabel( "Open" ); buttonWindow.setVisible( false ); } else { display.setLabel( "Close" ); buttonWindow.setVisible( true ); } } } }
Applets and Windows Continued This is the window opened by the applet on the previous slide.
class ButtonExample extends Frame { Button red = new Button( "Red" ); Button blue = new Button( "Blue" ); public ButtonExample( int widthInPixels, int heightInPixels ) { setTitle( "Button Example" ); setSize( widthInPixels, heightInPixels ); setLayout( new FlowLayout() ); add( red ); add( blue ); red.addActionListener( new ColorActionListener( Color.red) ); blue.addActionListener( new ColorActionListener( Color.blue) ); } class ColorActionListener implements ActionListener { Color backgroundColor; public ColorActionListener( Color aColor ) { backgroundColor = aColor; } public void actionPerformed( ActionEvent event ) { setBackground( backgroundColor ); repaint(); // Show effect of color change } } }
Communication with the Browser
The AppletContext provides the ability for the applet to ask the browser to perform tasks for the applet.
AppletContext Methods
getApplet(String)
getApplets()
getAudioClip(URL)
getImage(URL)
showDocument(URL)
showDocument(URL, String)
showStatus(String)
Note that the methods: getAudioClip(), getImage(), showStatus() in the Applet class call the corresponding methods in the AppletContext.
Displaying Items in the Browser
An applet can have the browser show pages.
import java.applet.*; import java.net.URL; import java.net.MalformedURLException; public class ShowDocumentApplet extends Applet { public void init( ) { try { URL wwwEli = new URL( "http://www.eli.sdsu.edu" ); AppletContext myContext = getAppletContext(); myContext.showDocument( wwwEli, "_blank"); } catch (MalformedURLException punt ) { } } }Values of Second Argument to showDocument
Argument
Meaning
"_self"
Show in the window and frame that contain the applet
"_parent"
Show in the parent frame. If the applet's frame has no parent, acts the same as "_self"
"_top"
Show in the topmost frame of the applet's window. If the applet's frame is the top-level, acts the same as "_self"
"_blank"
Show in a new unnamed top-level window.
name Show in the frame or window named name. If name does not exist, create a new top-level window named name, and show the document in itApplet-Applet Communication
Applets on the same page can communicate with each other. The following applet demonstrates how to do this. The InfoBus provides a more general way of doing this. See http://java.sun.com/beans/infobus/index.html for more information.HTML <APPLET ARCHIVE="AppletClasses.jar" CODE="Communication1Applet.class" WIDTH=100 HEIGHT=100> </APPLET><BR> <APPLET ARCHIVE="AppletClasses.jar" CODE="Communication2Applet.class" WIDTH=100 HEIGHT=100 NAME="sam"> </APPLET>Java Code import java.applet.*; import java.util.Enumeration; import java.awt.Graphics; import java.awt.event.*; import java.awt.Button; public class Communication2Applet extends Applet { String message = "Not set"; public void paint( Graphics display ) { display.drawString( message, 20, 20 ); } public void setMessage( String newMessage ) { message = newMessage; repaint(); } }
Applet Communication Continued public class Communication1Applet extends Applet { public void init( ) { AppletContext myContext = getAppletContext(); Communication2Applet partner; partner = (Communication2Applet) myContext.getApplet( "sam" ); partner.setMessage( "Hi mom" ); Button doIt = new Button( "Do it" ); add( doIt ); doIt.addActionListener( new DoItListener() ); } class DoItListener implements ActionListener { public void actionPerformed( ActionEvent event ) { Enumeration applets = getAppletContext().getApplets(); while ( applets.hasMoreElements() ) { Object applet = applets.nextElement(); if ( applet instanceof Communication2Applet ) ((Communication2Applet) applet).setMessage( "Did it"); } } } }
Output Note: all examples are done using the applet viewer
Images
HTML <APPLET ARCHIVE="AppletClasses.jar" CODE="ImageApplet.class" WIDTH=350 HEIGHT=100> </APPLET>Java Code import java.awt.*; import java.applet.Applet; import java.awt.Image; public class ImageApplet extends Applet{ private Image ioStream; private String errorMessage = null; public void init() { try { ioStream = getImage( getCodeBase(), "IO1002.gif" ); MediaTracker tracker = new MediaTracker( this ); tracker.addImage( ioStream, 0 ); tracker.waitForID( 0 ); System.out.println("Ready" ); repaint(); } catch (InterruptedException netProblem ) { errorMessage = "Could not reach image"; } } public void paint( Graphics display) { if ( errorMessage == null ) display.drawImage( ioStream, 0, 0, this ); else display.drawString( errorMessage, 10, 10 ); } }
Output Note: all examples are done using the applet viewer
Applet as Application
The following class, modified from the text (page 22-23), runs an applet as an application. This class has problems.
import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class SimpleAppletApplication extends Frame { Applet appletApp; public SimpleAppletApplication( String windowTitle, int width, int height, Applet anApplet ) { super( windowTitle ); setSize( width, height ); appletApp = anApplet; appletApp.init(); add( BorderLayout.CENTER, appletApp ); addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent event ) { dispose(); } } ); } public void show() { super.show(); appletApp.start(); } public void dispose() { appletApp.stop(); super.dispose(); appletApp.destroy(); }
Applet as Application Continued
public static void main(String[] args ) { Frame application = new SimpleAppletApplication( "Test", 200, 100, new HelloApplet() ); application.show(); } }
Better Applet Application The following class allows the applet to interact with its AppletContext. It still needs more work.
import java.awt.*; import java.applet.*; import java.awt.event.*; import java.net.URL; import java.util.Properties; import java.util.Enumeration; public class AppletFrame extends Frame implements AppletStub, AppletContext { // Store applet parameters Properties parameters = new Properties(); Applet appletApp; public AppletFrame( String windowTitle, int width, int height, Applet anApplet ) { super( windowTitle ); setSize( width, height ); appletApp = anApplet; appletApp.init(); add( BorderLayout.CENTER, appletApp ); } public void show() { super.show(); appletApp.start(); } public void dispose() { appletApp.stop(); super.dispose(); appletApp.destroy(); }
Better Applet Application Continued public void setParameters( Properties newParameters ) { parameters = newParameters; } // AppletStub methods public boolean isActive() { return true; } public URL getDocumentBase() { return null; //Need better default policy } public URL getCodeBase() { return null; //Need better default policy } public String getParameter( String name ) { String defaultValue = ""; return parameters.getProperty( name, defaultValue ); } public AppletContext getAppletContext() { return this; } public void appletResize( int width, int height ) { super.setSize( width, height ); super.invalidate(); super.validate(); }
Better Applet Application Continued // AppletContext methods public AudioClip getAudioClip(URL audioURL ) { return null; //Need better default policy } public Image getImage(URL imageURL ) { // Need better policy to handle applet URL to // local image file return Toolkit.getDefaultToolkit().getImage( imageURL ); } public Applet getApplet( String name ) { return null; } public Enumeration getApplets() { return null; } public void showDocument( URL pageURL ) { } public void showDocument( URL pageURL, String target ) { } public void showStatus( String status ) {} }
The Browser Mess & Java Plug-in
Different browsers support different versions of the JDK. The browsers have not been able to keep up with the changes in Java. To "improve" the situation, Sun provides a "plug-in" to add to browsers which allows the browsers to use Sun's JVM. You can download the plug-in at: http://java.sun.com/products/plugin/index.html
However, to use the plug-in the HTML files must use special tags. The tags are browser specific. More information about the tags can be found at: http://java.sun.com/products/plugin/1.2/docs/tags.html. There is a converter to add the new tags for you. The converter can be found at: http://java.sun.com/products/plugin/1.2/features.html
Java Plug-in for IE on Windows 95, 98 or NT 4.0
Original APPLET tag:
<APPLET code="XYZApp.class" codebase="html/" align="baseline" width="200" height="200"> <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz"> No JDK 1.2 support for APPLET!! </APPLET>
New OBJECT tag:
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="200" height="200" align="baseline" codebase="http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab#Version=1,2,0,0"> <PARAM NAME="code" VALUE="XYZApp.class"> <PARAM NAME="codebase" VALUE="html/"> <PARAM NAME="type" VALUE="application/x-java-applet;version=1.2"> <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz"> No JDK 1.2 support for APPLET!! </OBJECT>
Java Plug-in for Navigator 3 or 4
Original APPLET tag:
<APPLET code="XYZApp.class" codebase="html/" align="baseline" width="200" height="200"> <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz"> No JDK 1.2 support for APPLET!! </APPLET>
New EMBED tag:
<EMBED type="application/x-java-applet;version=1.2" width="200" height="200" align="baseline" code="XYZApp.class" codebase="html/" model="models/HyaluronicAcid.xyz" pluginspage="http://java.sun.com/products/plugin/1.2/plugin-install.html"> <NOEMBED> No JDK 1.2 support for APPLET!! </NOEMBED> </EMBED>
Java Plug-in for IE & Navigator 3 & 4 Original APPLET tag:
<APPLET code="XYZApp.class" codebase="html/" align="baseline" width="200" height="200"> <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz"> No JDK 1.2 support for APPLET!! </APPLET>
New tag:
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="200" height="200" align="baseline" codebase="http://java.sun.com/products/plugin/1.2/jinstall-12-win32.cab#Version=1,2,0,0"> <PARAM NAME="code" VALUE="XYZApp.class"> <PARAM NAME="codebase" VALUE="html/"> <PARAM NAME="type" VALUE="application/x-java-applet;version=1.2"> <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz"> <COMMENT> <EMBED type="application/x-java-applet;version=1.2" width="200" height="200" align="baseline" code="XYZApp.class" codebase="html/" model="models/HyaluronicAcid.xyz" pluginspage="http://java.sun.com/products/plugin/1.2/plugin-install.html"> <NOEMBED> </COMMENT> No JDK 1.2 support for APPLET!! </NOEMBED></EMBED> </OBJECT>
Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.
visitors since 07-Dec-98