Tải bản đầy đủ - 0 (trang)
4-4. Responding to HTML Events

4-4. Responding to HTML Events

Tải bản đầy đủ - 0trang

CHAPTER 4  JAVAFX ON THE WEB



Weather weather = parse(webEngine.getDocument());

warningMessage.setText("Warning: " + weather.currentWeatherText + "\nTemp: " +

weather.temperature + "\n E-mailed others");

... // the rest of changed() method

}); // end of addListener method

This code sets the OnAlert property, which is an event handler to respond when a the Panic or Calm

Down button is pressed:

webView.getEngine().setOnAlert(new EventHandler>(){

public void handle(WebEvent evt) {

warningMessage.setOpacity("warning".equalsIgnoreCase(evt.getData()) ? 1d :

0d);

}

}); // end of setOnAlert() method.

root.getChildren().addAll(webView, warningMessage);

stage.setScene(scene);

stage.show();

} // end of start() method

The following method is code that you will add as a private method that is responsible for creating a

text node (javafx.scene.text.Text) to be used as the warning message when the user presses the Panic

Button:

private Text createMessage(Color color, String message) {

DropShadow dShadow = DropShadowBuilder.create()

.offsetX(3.5f)

.offsetY(3.5f)

.build();

Text textMessage = TextBuilder.create()

.text(message)

.x(100)

.y(50)

.strokeWidth(2)

.stroke(Color.WHITE)

.effect(dShadow)

.fill(color)

.font(Font.font(null, FontWeight.BOLD, 35))

.translateY(50)

.build();

return textMessage;

}

} // end of the RespondingToHtmlEvents class

Figure 4-10 shows our weather application displaying a warning message after the Panic Button has

been pressed. To remove the warning message, you can press the Calm Down button.



161



CHAPTER 4  JAVAFX ON THE WEB



Figure 4-10.Weather application displaying warning message



How It Works

In this recipe you will add additional features to the weather application (from recipe 4-3) that responds

to HTML events. The application you will be creating is similar to the previous recipe, except you will be

adding HTML buttons on the web page to be rendered onto the WebView node. The first button added is

the Panic Button that, when pressed, displays a warning message stating the current weather condition

and a simulated e-mail notification to your cube mates. To retract the warning message you will also add

a Calm Down button.



 Note Because the code is so similar to the previous recipe, I will point out the additions to the source code

without going into great detail.



To add the buttons, you will use the HTML tag 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("
\n");

template.append("
Button\" />\n");

template.append("
down\" />\n");

template.append("
\n");



162



CHAPTER 4  JAVAFX ON THE WEB



When the web page renders allowing you to press the buttons, the onclick attribute will call

JavaScript’s alert() function that contains a string message. When the alert() function is invoked, the

web page’s owning parent (the webView’sWebEngine instance) will be notified of the alert via the

WebEngine’s OnAlert attribute. To respond to JavaScript’s alerts, you will add an event handler

(EventHandler) to respond to WebEvent objects. In the handle() method, you will simply show and hide

the warning message by toggling the opacity of the warningMessage 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, set to 0 (both of type

double).

webView.getEngine().setOnAlert(new EventHandler>(){

public void handle(WebEvent evt) {

warningMessage.setOpacity("warning".equalsIgnoreCase(evt.getData()) ? 1d : 0d);

}

});

Please see the Javadocs for additional HTML web events (WebEvent).



4-5. Displaying Content from the Database

Problem

You want to keep up on the latest news monitoring the local legislature and science regarding the

detrimental effects of the lack of light in small cubical work areas.



Solution

Create a JavaFX RSS reader. The RSS feed location URLs will be stored in a database to be later retrieved.

Listed here are the main classes used in this recipe:





javafx.scene.control.Hyperlink







javafx.scene.web.WebEngine







javafx.scene.web.WebView







org.w3c.dom.Document







org.w3c.dom.Node







org.w3c.dom.NodeList



This recipe will be using an embedded database called Derby from the Apache group at

http://www.apache.org. As a requirement, you will need to download the Derby software. To download

the software, visit http://db.apache.org/derby/derby_downloads.html to download the latest version

containing the libraries. Once downloaded, you can unzip or untar into a directory. To compile and run

this recipe, you will need to update the classpath in your IDE or environment variable to point to Derby

libraries (derby.jar and derbytools.jar). You can type a valid RSS URL into the text field when running

the example code, and then hit the enter key to load your new RSS headlines. After loading is complete,



163



CHAPTER 4  JAVAFX ON THE WEB



the headline news is listed to the upper right frame region. Next, you will have an opportunity to choose

a headline news article to read fully by clicking on a view button beneath it.

The following code implements an RSS reader in JavaFX:

package javafx2introbyexample.chapter4.recipe4_05;

import

import

import

import

import

import

import

import

import

import

import

import

import

import

import

import

import



java.util.*;

javafx.application.Application;

javafx.beans.value.*;

javafx.collections.ObservableList;

javafx.concurrent.Worker.State;

javafx.event.*;

javafx.geometry.*;

javafx.scene.*;

javafx.scene.control.*;

javafx.scene.input.*;

javafx.scene.layout.*;

javafx.scene.paint.Color;

javafx.scene.web.*;

javafx.stage.Stage;

org.w3c.dom.Document;

org.w3c.dom.Node;

org.w3c.dom.NodeList;



/**

* Display Contents From Database

* @author cdea

*/

public class DisplayContentsFromDatabase extends Application {

@Override

Group

Scene

final



public void start(Stage stage) {

root = new Group();

scene = new Scene(root, 640, 480, Color.WHITE);

Map hyperLinksMap = new TreeMap<>();



final WebView newsBrief = new WebView(); // upper right

final WebEngine webEngine = new WebEngine();

final WebView websiteView = new WebView(); // lower right

webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener() {

public void changed(ObservableValue observable, State oldValue,

State newValue){

if (newValue != State.SUCCEEDED) {

return;

}

RssFeed rssFeed = parse(webEngine.getDocument(), webEngine.getLocation());

hyperLinksMap.get(webEngine.getLocation()).setText(rssFeed.channelTitle);

// print feed info:

StringBuilder rssSource = new StringBuilder();



164



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

4-4. Responding to HTML Events

Tải bản đầy đủ ngay(0 tr)

×