Java Reference
In-Depth Information
ject to be displayed as HTML. The following code snippet instantiates a
WebView
graph node that is responsible for rendering the HTML5 content:
final WebView webView = new WebView();
The countdown timer in the example refreshes the weather information being dis-
played in the application window. First, you instantiate an
IntegerProperty
vari-
able, called
countdown,
to hold the number of seconds until the next refresh time.
Second, you add a change listener (
ChangeListener
) to update the HTML content
dynamically using JavaFX's capability to execute JavaScript. The change listener also
determines whether the countdown has reached zero. If so, it invokes the
webEngine
's (
WebEngine
)
reload()
method to refresh or retrieve the weather
information again. The following code creates an
IntegerProperty
value to up-
date the countdown text using the
executeScript()
method:
IntegerProperty countDown = new
SimpleIntegerProperty(refreshCountdown);
countDown.addListener((ObservableValue<? extends Number>
observable,
Number oldValue, Number newValue) -> {
webView.getEngine().executeScript(
"document.getElementById('countdown').innerHTML
= 'Seconds till refresh: "
+ newValue + "'");
if (newValue.intValue() == 0) {
webEngine.reload();
}
}); // addListener()
After the
ChangeListener
is implemented using a lambda expression, a
TimeLine
object is created to change the
countdown
variable, which will trigger
the
ChangeListener
to update the HTML text depicting the seconds until refresh.
The following code implements a
TimeLine
object that updates the
countDown
variable:
final Timeline timeToRefresh = new Timeline();
timeToRefresh.getKeyFrames().addAll(
new KeyFrame(Duration.ZERO, new KeyValue(countDown,