How to wait for WebEngine/Browser initialization in JavaFx application?

ぐ巨炮叔叔 提交于 2019-12-08 05:38:56

问题


I would like to create a custom FunctionPlotter component that is based on the JavaFx WebEngine. My plots will be shown in a browser. Before I execute my plot commands I have to wait until the browser has been initialized (it loads d3.js). Currently I do so by putting my plot expressions in a Runnable and pass that runnable to the FunctionPlotter. (The FunctionPlotter passes the runnable to the loading finished hook of the browser):

private FunctionPlotter plotter;
...

Runnable plotRunnable = ()->{
    plotter.plot("x^2");
}

plotter = new FunctionPlotter(plotRunnable);

However I would prefer following (blocking) work flow for the usage of my FunctionPlotter component:

Functionplotter plotter = new FunctionPlotter();
plotter.plot("x^2")

=> The FunctionPlotter should automatically wait until the wrapped browser has been initialized.

How should I do this in an JavaFx Application?

Inside the FunctionPlotter I could do something like

private Boolean isInitialized = false
...

ReadOnlyObjectProperty<State> state =  webEngine.getLoadWorker().stateProperty();
state.addListener((obs, oldState, newState) -> {
    boolean isSucceeded = (newState == Worker.State.SUCCEEDED);
    if (isSucceeded) {
        isInitialized = true;
    }
});
webEngine.loadContent(initialBrowserContent);

waitUntilInitialLoadingIsFinished();

My actual question is how the method on the last line could be implemented. If I use following code, the application will wait for ever:

private void waitUntilBrowserIsInitialized() {
    while(!isInitialized){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }
}

I know that there is stuff like JavaFx Tasks, Platform.runLater(), Service, CountdownLatch (JavaFX working with threads and GUI) but those did not help me (= I did not get it working). How can I wait in the main Thread until a Runnable is finished?

Here someone says that the JavaFx Application thread should never be blocked:

Make JavaFX application thread wait for another Thread to finish

Any other suggestions?

Edit

Related question: JavaFX/SWT WebView synchronous loadcontent()


回答1:


I decided to wrap the plot functionality in an internal queue of plot instructions. The command

plotter.plot("x^2");

will not actually execute the plot but add a plot instruction to the queue. After the browser has been initialized, that queue will be worked through and the plot commands will be executed with a delay. While the browser is initializing I will show some kind of progress bar.

If you know a solution that does not need this delayed execution work around please let me know.



来源:https://stackoverflow.com/questions/33971137/how-to-wait-for-webengine-browser-initialization-in-javafx-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!