2

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()

Community
  • 1
  • 1
Stefan
  • 10,010
  • 7
  • 61
  • 117

1 Answers1

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.

Stefan
  • 10,010
  • 7
  • 61
  • 117