Java Reference
In-Depth Information
JavaFX and JavaScript Interaction
Interaction between a JavaFX applet and JavaScript on the HTML page is fairly
simple and two-way interaction is supported. From the JavaFX applet, you can
invoke arbitrary JavaScript on the Web page. On the other hand, from JavaScript
on the Web page, you can get and set variables and invoke functions on the
JavaFX applet.
JavaFX to JavaScript
First, let's discuss the JavaFX to JavaScript interaction. The javafx.stage
.AppletStageExtension class that we used in our “undocking” exercise earlier
also contains a function, eval() , that takes a string argument of JavaScript code.
This is executed in the HTML document that hosts the JavaFX applet. If the Java-
Script code returns an object, eval() returns it. Let's look at an example using
the NASAImageBrowser applet.
First, let's add a read-only text field to the HTML page, identified as "numPics" .
This field will hold the total number of pictures that the NasaImageBrowser
applet currently has. The HTML code is in Listing 9.7.
Listing 9.7
HTML - Input Type “id”
<p>Number of pictures:
<input type="text" name="numPics" readonly="readonly"
id="numPics" value="0" size="10" >
To update this field from the JavaFX code, we bind a variable to the size of the
image list. When the image list size is updated, we invoke a JavaScript function
that sets the value of the read-only field, "numPics" . The JavaFX code is in List-
ing 9.8.
Listing 9.8
JavaFX Script - Locate JavaScript Item by ID
var applet: AppletStageExtension;
public var totalImageCount =
bind sizeof imageList.images on replace {
applet.eval("document.getElementById('numPics').value =
{totalImageCount}");
};
The applet variable is assigned to the AppletStageExtension when we created
the stage, as shown in Listing 9.9.
 
 
Search WWH ::




Custom Search