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 Applet Methods From JavaScript Code

JavaScript code on a web page can interact with Java applets embedded on the page. JavaScript code can perform operations such as the following:

TheLiveConnect Specification describes details about how JavaScript code communicates with Java code.

Security warnings are shown when JavaScript code makes calls to a Java applet. To suppress these warnings, add theCaller-Allowable-Codebase attribute to the JAR file manifest. Specify the location of the JavaScript code that is allowed to make calls to the applet. SeeJAR File Manifest Attributes for Security for information about theCaller-Allowable-Codebase attribute.

This topic explores JavaScript code to Java applet communication using the Math applet example. TheMathApplet class and supportingCalculator class provide a set of public methods and variables. The JavaScript code on the web page invokes and evaluates these public members to pass data and retrieve calculated results.

Math Applet and Related Classes

Here is the source code for theMathApplet class. ThegetCalculator method returns a reference to theCalculator helper class.

 package jstojava;import java.applet.Applet;public class MathApplet extends Applet{    public String userName = null;             public String getGreeting() {        return "Hello " + userName;    }        public Calculator getCalculator() {        return new Calculator();    }         public DateHelper getDateHelper() {        return new DateHelper();    }        public void printOut(String text) {        System.out.println(text);    }}

The methods in theCalculator class let the user set two values, add numbers, and retrieve the numbers in a range.

package jstojava;public class Calculator {    private int a = 0;    private int b = 0; // assume b > a        public void setNums(int numA, int numB) {        a = numA;        b = numB;    }        public int add() {        return a + b;    }        public int [] getNumInRange() {            int x = a;        int len = (b - a) + 1;        int [] range = new int [len];        for (int i = 0; i < len; i++) {            range[i]= x++;            System.out.println("i: " + i + " ; range[i]: " + range[i]);        }        return range;    }}

ThegetDate method of theDateHelper class returns the current date.

package jstojava;import java.util.Date;import java.text.SimpleDateFormat;public class DateHelper {        public static String label = null;            public String getDate() {        return label + " " + new SimpleDateFormat().format(new Date());    }}

Deploying the Applet

Deploy the applet in a web page,AppletPage.html When deploying the applet, make sure that you specify an id for the applet. The applet id is used later to obtain a reference to the applet object.

<script src=  "https://www.java.com/js/deployJava.js"></script><script>    <!-- applet id can be used to get a reference to    the applet object -->    var attributes = {id:'mathApplet',        code:'jstojava.MathApplet',  width:1, height:1} ;    var parameters = { jnlp_href: 'math_applet.jnlp'} ;    deployJava.runApplet(attributes, parameters, '1.6');</script>

Next, add some JavaScript code to theAppletPage.html web page. The JavaScript code can use the applet id as a reference to the applet object and invoke the applet's methods. In the example shown next, the JavaScript code sets the applet's public member variables, invokes public methods, and retrieves a reference to another object referenced by the applet (Calculator). The JavaScript code is able to handle primitive, array, and object return types.

<script language="javascript">    function enterNums(){        var numA = prompt('Enter number \'a\'?','0');        var numB = prompt(            'Enter number \'b\' (should be greater than number \'a\' ?','1');        // set applet's public variable        mathApplet.userName = "John Doe";        // invoke public applet method        var greeting = mathApplet.getGreeting();        // get another class referenced by applet and        // invoke its methods        var calculator = mathApplet.getCalculator();        calculator.setNums(numA, numB);        // primitive datatype returned by applet        var sum = calculator.add();        // array returned by applet        var numRange = calculator.getNumInRange();        // check Java console log for this message        mathApplet.printOut("Testing printing to System.out");        // get another class, set static field and invoke its methods        var dateHelper = mathApplet.getDateHelper();        dateHelper.label = "Today\'s date is: ";        var dateStr = dateHelper.getDate();        <!-- ... --></script>

The Math applet displays the following results on the web page when the number a = 0 and b = 5:

Results of JavaScript to Java CommunicationHello John Doea = 0 ; b = 5Sum: 5Numbers in range array: [ 0, 1, 2, 3, 4, 5 ]Today's date is: 5/28/13 4:12 PM //shows current date

OpenAppletPage.html in a browser to view the Math 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.

Checksecurity restrictions placed on applets invoked by JavaScript code.

Download source code for theInvoking Applet Methods From JavaScript Code 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: Invoking JavaScript Code From an Applet
Next page: Handling Initialization Status With Event Handlers

[8]ページ先頭

©2009-2025 Movatter.jp