Handling page loading progress with LoadWorker 

The WebEngine.getLoadWorker() method returns a Worker object that tracks the progress of the page loading.

The most important properties of Worker are the following:

  • progressProperty: This represents the page loading progress
  • stateProperty: This represents the status of the loading process, especially Worker.State.FAILED and Worker.State.SUCCEEDED

In the next example, we will use these properties to add a progress loading indicator and messages about the end of the page loading:

// chapter9/web/LoadWorkerDemo.java
public void start(Stage primaryStage) {
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.load("https://stackoverflow.com/questions/tagged/javafx");

ProgressBar loadingBar = new ProgressBar(0);
loadingBar.setMinWidth(400);

// using binding to easily connect the worker and the progress bar
loadingBar.progressProperty().bind(
webEngine.getLoadWorker().progressProperty());

webEngine.getLoadWorker().stateProperty().addListener(
(observable, oldValue, newValue) -> {
if (newValue == Worker.State.SUCCEEDED) {
System.out.println("Page was successfully loaded!");
} else if (newValue == Worker.State.FAILED) {
System.out.println("Page loading has failed!");
}

});

    VBox root = new VBox(5, loadingBar, webView);
primaryStage.setTitle("JavaFX on SO");
primaryStage.setScene(new Scene(root, 400, 300));
primaryStage.show();
}

Here is a screenshot of the application in the middle of loading. Note the progress bar at the top:

It's very important to wait for Worker.State.SUCCEEDED before starting any work with web page content—both HTML and JavaScript. It's similar to the JavaScript practice of writing code in the document.onload() method.

Another way to wait for page loading is the workDone property:

webEngine.getLoadWorker().workDoneProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.intValue() == 100) {
// page is 100% loaded
}
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.247.181