Tab webViewTab = new Tab("WebView");
webViewTab.setContent(webView);
webViewTab.setClosable(false);
webViewTab.setOnSelectionChanged(e -> {
String randomWebSite = model.getRandomWebSite();
if (webViewTab.isSelected()) {
webView.getEngine().load(randomWebSite);
System.out.println("WebView tab is selected, loading: "
+ randomWebSite);
}
});
Using a WebView
The WebView control is a web browser that you can embed in JavaFX applications. As you experienced in Steps 34 and 35 of the exercise, the WebView control shown in Figure 6-14 automatically displays a randomly selected web page when the tab labeled PasswordField is selected.
In the following snippet from Listing 6-5, the WebView created earlier is assigned to the Tab’s content and properties are assigned, including the lambda expression that is called when the tab is selected.
The code in the onSelectionChanged() method earlier calls a method in the StarterAppModel class to get the URL of a randomly selected web site. The getEngine() method of the WebView is then invoked to get the WebEngine instance associated with the WebView. The load() method of the WebEngine is invoked, passing a String that contains the randomly selected URL, which causes the WebView to display the web page retrieved from that URL. The following snippet contains the relevant code from the StarterAppModel class:
public String getRandomWebSite() {
String[] webSites = {
"http://javafx.com",
"http://fxexperience.com",
"http://steveonjava.com",
"http://javafxpert.com",
"http://pleasingsoftware.blogspot.com",
"http://weiqigao.blogspot.com/",
"http://blogs.lodgon.com/johan",
"http://google.com"
};
int randomIdx = (int)(Math.random() * webSites.length);
return webSites[randomIdx];
}
The WebView control and its WebEngine counterpart have additional capabilities documented in the javafx.scene.web package of the API that are worth investigating.