Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Java Applets
Getting Started With Applets
Defining an Applet Subclass
Methods for Milestones
Life Cycle of an Applet
Applet's Execution Environment
Developing an Applet
Deploying an Applet
Deploying With the Applet Tag
Doing More With Applets
Finding and Loading Data Files
Defining and Using Applet Parameters
Displaying Short Status Strings
Displaying Documents in the Browser
Invoking JavaScript Code From an Applet
Invoking Applet Methods From JavaScript Code
Handling Initialization Status With Event Handlers
Manipulating DOM of Applet's Web Page
Writing Diagnostics to Standard Output and Error Streams
Developing Draggable Applets
Communicating With Other Applets
Working With a Server-Side Application
Network Client Applet Example
What Applets Can and Cannot Do
Solving Common Applet Problems
Questions and Exercises
Trail: Deployment
Lesson: Java Applets
Section: Doing More With Applets
Home Page >Deployment >Java Applets
« Previous • Trail • Next »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Invoking JavaScript Code From an Applet

Java applets can invoke JavaScript functions present in the same web page as the applet. TheLiveConnect Specification describes details about how JavaScript code communicates with Java code.

Thenetscape.javascript.JSObject class enables Java applets to retrieve a reference to JavaScript objects and interact with the web page. The Data Summary applet described next invokes JavaScript code to retrieve information from the web page and writes a data summary back to the web page.

Assume you have a web page with a few JavaScript functions. The exampleAppletPage.html has JavaScript functions to retrieve age, address, and phone numbers. There is also a variable calleduserName which has no value at the outset.

<head><title>Data Summary Applet Page - Java to JavaScript LiveConnect</title><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/><script language="javascript">    var userName = "";        // returns number    function getAge() {         return 25;    }    // returns an object    function address() {         this.street = "1 Example Lane";        this.city = "Santa Clara";        this.state = "CA";    }    // returns an array    function getPhoneNums() {         return ["408-555-0100", "408-555-0102"];    }     function writeSummary(summary) {        summaryElem =            document.getElementById("summary");        summaryElem.innerHTML = summary;    }    </script>    <!-- ... -->      </head><body>    <script src =      "https://www.java.com/js/deployJava.js"></script>    <script>         <!-- ... -->        deployJava.runApplet(attributes, parameters, '1.6');     </script>              <!-- ... -->    <p/>  // this HTML element contains                             // the summary     <!-- ... --></body>

Next, consider an applet class calledDataSummaryApplet. TheDataSummaryApplet class performs the following operations.

This applet first needs to retrieve a reference toJSObject as follows:

...JSObject window = JSObject.getWindow(this);...

Put the preceding statement in a try ...catch.. block to handlenetscape.javascript.JSException.

Now that the applet has a reference toJSObject, it can invoke the relevant JavaScript functions by using theeval andcall methods ofJSObject.

package javatojs;import java.applet.Applet;import netscape.javascript.*; // add plugin.jar to classpath during compilationpublic class DataSummaryApplet extends Applet {    public void start() {        try {            JSObject window = JSObject.getWindow(this);            String userName = "John Doe";            // set JavaScript variable            window.setMember("userName", userName);            // invoke JavaScript function            Number age = (Number) window.eval("getAge()");            // get a JavaScript object and retrieve its contents            JSObject address = (JSObject) window.eval("new address();");            String addressStr = (String) address.getMember("street") + ", " +                    (String) address.getMember("city") + ", " +                    (String) address.getMember("state");            // get an array from JavaScript and retrieve its contents            JSObject phoneNums = (JSObject) window.eval("getPhoneNums()");            String phoneNumStr = (String) phoneNums.getSlot(0) + ", " +                    (String) phoneNums.getSlot(1);            // dynamically change HTML in page; write data summary            String summary = userName + " : " + age + " : " +                    addressStr + " : " + phoneNumStr;            window.call("writeSummary", new Object[] {summary})   ;        } catch (JSException jse) {            jse.printStackTrace();        }    }}

To compile Java code that has a reference to classes in thenetscape.javascript package, include<your JDK path>/jre/lib/plugin.jar in your classpath. At runtime, the Java Plug-in software automatically makes these classes available to applets.

The Data Summary applet displays the following result on the web page:

Result of applet's Java calls to JavaScript on this page                John Doe : 25 : 1 Example Lane, Santa Clara, CA : 408-555-0100, 408-555-0102

OpenAppletPage.html in a browser to view the Data Summary applet .


Note:  If you don't see the applet running, you need to install at least theJava SE Development Kit (JDK) 6 update 10 release.

Note:  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.

Download source code for theInvoking JavaScript Code From Applet example to experiment further.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

Previous page: Displaying Documents in the Browser
Next page: Invoking Applet Methods From JavaScript Code

[8]ページ先頭

©2009-2025 Movatter.jp