Applets can obtain additional services from an AppletContext
object, which returns from the method
getAppletContext
()
in the java.awt.Applet
class. The methods of the AppletContext
interface include:
- getApplets
() - returns an enumeration
of references to other applets running on same html page.
- getApplet
(String name) - returns a reference to the
applet called name used in the Name
attribute in the applet tag.
- showDocument
(URL url)
showDocument (URL url, String target) - loads the
web page linked to the url. In the first case the applet page
will be replaced. In the second case, target can be
- "_self"
- show in current frame
- "_parent"
- show in parent container
- "_top"
- show in topmost
frame
- "_blank"
- show in a new, top-level window
- "string"
- show in a frame with that string name.
- showStatus
(String msg) - show the string msg
on the bottom edge status line of the browser frame.
- getImage
(URL url), getAudioClip (URL
url)
- return image and audioclip references, rsp.
The Applet
class itself implements the AppletContext
interface and provides the showStatus(),
getImage() and
getAudioClip() methods.
Note that the URL does not need to point just to the domain where
the applet originated but can point to any web address.
The getApplet()
and getApplets()
methods allow for inter-applet communication when multiple applets
are running on the same page.
Note that some browsers don't permit this for security reasons.
Creating
Your Own AppletViewer
If you put an applet into a frame for a standalone application
and the applet needs to invoke methods such as getImage(),
you must implement the AppletContext
and also the AppletStub
interface.
This might be useful for situations where you want
quickly to build a specialized application from an applet with little
or no changes to the applet code.
Also, for testing network applets you could bypass
the JDK appletviewer's SecurityManager restrictions.
To make a viewer you need to implement methods in
these two interfaces:
- AppletStub
- methods to interface to the viewer or browser
- AppletContext
- methods that provide document information
A stub provides an intermediary between two sets
of code.
This example below implements the getCodeBase()
and getDocumentBase()
methods in the AppletStub
interface and the getImage()
method in the AppletContext()
method.
For the other methods it returns empty values. For
applets that need these methods, you could code them appropriately.
|
import
javax.swing.*;
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.util.*;
/**
* Illustrates how a JFrame subclass
can implement the
* AppletStub & AppletContext interfaces
to build a
* rudimentary appletviewer.
*
* Here the getDocumentBase (), getImage
(URL url), and
* getCodeBase () were implemented
in detail. You will
* need to implement the other methods
as needed.
**/
public class StartJAppletViewer extends JFrame
implements ActionListener, AppletStub, AppletContext
{
/** Create a menubar for the frame and a File
menu. **/
StartJAppletViewer () {
setTitle ("MyAppletViewer");
JMenu m = new JMenu ("File");
JMenuItem mi = new JMenuItem ("Quit");
mi.addActionListener (this);
m.add (mi);
JMenuBar mb = new JMenuBar ();
mb.add (m);
setJMenuBar (mb);
} // ctor
// AppletStub methods
/**
* Use the File class (See
lecture 9) and the System properties
* to create a URL from the current
working directory.
**/
public URL getDocumentBase () {
URL url = null;
try {
File file = new File
(System.getProperty ("user.dir"));
url = file.toURL ();
}
catch (MalformedURLException
e) {
System.out.println
("Bad URL");
url = null;
}
return url;
} // getDocumentBase
/** Provide getCodeBae that returns a URL
* that points to the local directory
where
* this program is running.
**/
public URL getCodeBase () {
URL url = null;
try {
File file = new File
(System.getProperty ("user.dir"));
url = file.toURL ();
System.out.println
("url="+url);
}
catch (MalformedURLException
e) {
System.out.println
("Bad URL");
url = null;
}
return url;
} // getCodeBase
// Note: ignore the warning that there is also
a private isActive
// method in the java.awt.Window class.
public boolean isActive () { return true;}
public String getParameter (String name) {
return ""; }
public AppletContext getAppletContext () {
return this; }
public void appletResize (int width, int height)
{}
// AppletContext methods
// Use the toolkit to get the image from the
local directory
public Image getImage (URL url) {
String imgName = url.getFile ();
return Toolkit.getDefaultToolkit
().getImage (imgName);
}
public AudioClip getAudioClip (URL url) { return
null; }
public Applet getApplet (String name) { return
null; }
public Enumeration<Applet> getApplets ()
{ return null; }
public void showDocument (URL url) {}
public void showDocument (URL url, String target)
{}
public void showStatus (String status) {}
// New AppletContext methods added in vers.1.4
public void setStream (String key, InputStream
stream){}
public Iterator<String> getStreamKeys ()
{ return null; }
public InputStream getStream (String key){
return null; }
/**
* Create the viwer and load the
applet into it.
**/
public static void main (String [] args) {
// Create an instance of this frame
class for holding the applet
StartJAppletViewer viewer = new
StartJAppletViewer ();
// Replace "_JApplet" with the applet
of interest.
_JApplet applet = new _JApplet ();
applet.setStub (viewer);
// Call init () to do whatever initialization
can be
// done outside of a browser environment.
applet.init ();
viewer.add ("Center", applet);
viewer.setDefaultCloseOperation
(JFrame.DISPOSE_ON_CLOSE);
viewer.pack ();
viewer.setSize (300,300);
viewer.setVisible (true);
} // main
public void actionPerformed (ActionEvent e )
{
if ( e.getActionCommand ().equals
("Quit") )
dispose
();
System.exit (0);
} // actionPerformed
} // class StartJAppletViewer
|
For AWT cases, the StartAppletViewer.java
code is available here.
If the applet doesn't need the AppletContext
methods, then you can use a simpler frame starter such as StartJApp2.java
(StartApp5.java
for non-Swing applets)
You could go to the next step in creating an applet viewer by allowing
the user to put the name of a hypertext file on the command line.
You could then use the string search tools (see Chapter
10: Java : String Tools) to find the applet tags and decode
them to find the applet class name, the dimensions of the applet
window, and the parameters if any.
You will get the class name as a string. To then get the object
that it refers to, you must take advantage of the Class
class methods discussed in Chapter
5: Supplements: Class
Class.
To illustrate this, we offer the program MyJAppletViewer,
which expects an applet class name on the command line, e.g.
c:\>
java MyJAppletviewer HelloWorld
where HelloWorld.class
applet should be in the directory with MyJAppletviewer.
The main()
method looks for the class name as follows:
public
static void main (String [] args) {
if (args.length != 1) {
System.out.println
("Applet name missing!");
System.exit(0);
}
// Create an instance of this frame class
for holding the applet
MyJAppletViewer viewer = new MyJAppletViewer
();
// Replace "_JApplet" with the applet of
interest.
JApplet applet = (JApplet)getAppletFromString
(args[0]);
if (applet == null) {
System.out.println
("Error in finding applet class!");
System.exit(0);
}
applet.setStub (viewer);
... same as StartJAppletViewer ...
The method getAppletFromString
(args[0]) finds the class that corresponds to the string
with the following code:
/**
Create Applet object from string name. **/
static Applet getAppletFromString (String class_name)
{
Class c = null;
try {
c = Class.forName (class_name);
}
catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException:
" + e);
return null;
}
Applet applet = null;
try {
applet = (Applet) c.newInstance();
}
catch (InstantiationException e) {
System.out.println("InstantiationException:
" + e);
}
catch (IllegalAccessException e) {
System.out.println("IllegalAccessException:
" + e);
}
return applet;
}
This illustrates the power of the late binding aspect of
Java. It classes to be linked dynamically at runtime rather during
compilation.
References & Web Resources
Latest update: Dec. 7, 2004
|