Java Reference
In-Depth Information
node. The first button is the Panic button that, when pressed, displays a warning mes-
sage stating the current weather condition and a simulated e-mail notification. To re-
tract the warning message, you added a Calm Down button.
Note
Because the code is so similar to the previous recipe, I point out only the addi-
tions to the source code without going into great detail.
To add the buttons, you use the HTML tag
<input type=”button”...>
,
with an
onclick
attribute set to use JavaScript's
alert()
function to notify JavaFX
of an alert event. Shown here are the two buttons added to the web page:
StringBuilder template = new StringBuilder();
...// Header part of HTML Web page
template.append("<form>\n");
template.append(" <input type=\"button\"
onclick=\"alert('warning')\" value=\"Panic Button\"
/>\n");
template.append(" <input type=\"button\"
onclick=\"alert('unwarning')\" value=\"Calm down\" />\n");
template.append("</form>\n");
When the web page renders, the buttons can be clicked, invoking the
onclick
at-
tribute that will call JavaScript's
alert()
function containing the string message.
When the
alert()
function is invoked, the web page's owning parent (the
webView
's
WebEngine
instance) is notified of the alert via the
WebEngine
's
OnAlert
attribute. To respond to JavaScript's alerts, an event handler (lambda ex-
pression) is added. It responds to the
WebEvent
objects. The
handle()
method
simply shows and hides the warning message by toggling the opacity of the
warn-
ingMessage
node (
javafx.scene.text.Text
). The following code snippet
toggles the opacity of the warning message based on comparing the event's data
(
evt.getData()
) that contains the string passed in from the JavaScript's
alert()
function. So, if the message is
"warning"
, the
warningMessage
opacity is set to
1; otherwise, it's set to 0 (both of type
double
).
webView.getEngine().setOnAlert(new
EventHandler<WebEvent<String>>(){
public void handle(WebEvent<String> evt) {