Run JavaFX Controller in a separate thread


Question

Hi i need to upgrade GUI from SWT to JavaFX and have problem straight at the beginning. The main class inherits from Thread and is being run from a certain method (interface implementation):

@Override
public void mStart() {


    this.start();

}

@Override
public void mStop() {

    this.shell.dispose();

}

My FX GUI is created with SceneBuilder. Question is how to manage Controller to start in a different thread as it is instantiated automatically ?

1
1
1/16/2014 11:41:53 AM

Accepted Answer

After some research the conclusion is: JavaFX app can be run as a different thread from non FX app, just need to implement Runnable and insert launch() method into run(). Then offcourse do start() on thread that is responsible to launch your GUI. Then if want to update your controls (buttons, labels, panels etc) from within different thread you must do something like this:

Platform.runLater(new Runnable() {
      @Override public void run() {
        //Update UI here     
      }
    });

for more information read posts: here and here

4
5/23/2017 12:20:28 PM

Well, I never used the Scene Builder nor SWT, but one thing I'm sure:

The JavaFX application thread is responsible for taking care of any existing JavaFX element. You can find details on how to properly handle the JavaFX elements here. What I think you have to do is make sure to access JavaFX elements using the JavaFX application thread, which you can do using the method runLater from Platform class. Take a look:

http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html#runLater%28java.lang.Runnable%29

As always, we know we should start JavaFX applications from the main thread of a Java program. What you can do is to use the main thread in any point of your SWT application to call the initiator of your main JavaFX class. For example, at one point of your SWT application, all you have to do is call launch.

Do not forget, however, that the main thread (the one that should call launch) will be locked until your JavaFX application is finalized.

Hope this helps, and good luck. :)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon