文档

Java™ 教程-Java Tutorials 中文版
在浏览器中显示文档
Trail: Deployment
Lesson: Java Applets
Section: Doing More With Applets

在浏览器中显示文档

A Java applet can load a web page in a browser window using the showDocument methods in the java.applet.AppletContext class.

Here are the two forms of showDocument:

public void showDocument(java.net.URL url)
public void showDocument(java.net.URL url, String targetWindow)

The one-argument form of showDocument simply instructs the browser to display the document at the specified URL, without specifying the window in which to display the document.

The two-argument form of showDocument lets you specify the window or HTML frame in which to display the document. The second argument can have one of the folllowing values:


注意: In this discussion, frame refers not to a Swing JFrame, but to an HTML frame within a browser window.

The following applet enables you try every argument of both forms of showDocument. The applet opens a window that lets you type in a URL and choose an option for the targetWindow argument. When you press Return or click the Show document button, the applet calls showDocument.


注意: If you don't see the example running, you might need to enable the JavaScript interpreter in your browser so that the Deployment Toolkit script can function properly.

Following is the applet code that calls showDocument. Here is the whole program, ShowDocument.

        ...//In an Applet subclass:
        urlWindow = new URLWindow(getAppletContext());
        . . .

class URLWindow extends Frame {
    ...
    public URLWindow(AppletContext appletContext) {
        ...
        this.appletContext = appletContext;
        ...
    }
    ...
    public boolean action(Event event, Object o) {
        ...
            String urlString =
                /* user-entered string */;
            URL url = null;
            try {
                url = new URL(urlString);
            } catch (MalformedURLException e) {
                ...//Inform the user and return...
            }

            if (url != null) {
                if (/* user doesn't want to specify
                           the window */) {
                    appletContext.showDocument(url);
                } else {
                    appletContext.showDocument(url,
                        /* user-specified window */);
                }
            }
        ...

Download source codefor the Show Document example to experiment further.


Previous page: Displaying Short Status Strings
Next page: Invoking JavaScript Code From an Applet