Crossability Winmostar Support team.
JavaFX, Java's default GUI, has the ability to display web pages. In this article, I'll show you how. Web pages can be viewed using a class called WebView. Below is the sample code.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebTest extends Application {
private WebView webView;
@Override
public void start(Stage stage) {
this.webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.load("https://x-ability.co.jp");
BorderPane pane = new BorderPane(this.webView);
Scene scene = new Scene(pane, 500, 500);
stage.setScene(scene);
stage.setMaximized(true);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Use WebEngine # load to update the URL set in WebView.
private void updateURL(String url) {
WebEngine webEngine = this.webView.getEngine();
webEngine.load(url);
}
Use WebHistory # go to go back or forth on the page you are viewing.
private void goForward() {
WebEngine webEngine = this.webView.getEngine();
WebHistory webHistory = webEngine.getHistory();
webHistory.go(+1);
}
private void goBackward() {
WebEngine webEngine = this.webView.getEngine();
WebHistory webHistory = webEngine.getHistory();
webHistory.go(-1);
}
Implements JavaFX window closing process when a window closing event occurs from a web page. Use WebEngine # setOnVisibilityChanged.
@Override
public void start(Stage stage) {
...abridgement...
stage.show();
webEngine.setOnVisibilityChanged(event -> {
if (!event.getData()) {
stage.hide();
}
});
}
Implement the process to display a new window in JavaFX when an event to display a pop-up occurs from a web page. Use WebEngine # setCreatePopupHandler.
@Override
public void start(Stage stage) {
...abridgement...
stage.show();
webEngine.setCreatePopupHandler(config -> {
WebView webView2 = new WebView();
WebEngine webEngine2 = webView2.getEngine();
webEngine2.load("about:blank");
BorderPane pane2 = new BorderPane(webView2);
Scene scene2 = new Scene(pane2, 500, 500);
Stage stage2 = new Stage();
stage2.setScene(scene2);
stage2.show();
return webEngine2;
});
}
Recommended Posts