Search code examples
javajavafxgraphicsjava-threads

JavaFX without using a thread in the class


So far in all the JavaFX examples I've seen, the code uses some form of thread whether that is through extending Application or doing:

SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            initAndShowGUI(); //arbitrary function
        }
    });

in the main method. I was wondering if it was possible to avoid all of this and create a stand alone JavaFX class that can be called in the main class. (The main class does use a thread).

For instance, I am trying to draw some tiles and then use the PerspectiveCamera. However, I want the projection/view created to be written in a separate class, and then call an instance of that class in the main class.


Solution

  • If your code is touching / initialising a JavaFX component, then it must use the JavaFX platform thread. There's no way around this, this needs to be the case for JavaFX to work properly (otherwise you'll likely run into all sorts of odd thread-related bugs.)

    This is also the case with Swing, though in JavaFX this tends to be enforced much more thoroughly, with exceptions being thrown if you touch something from the wrong thread. This is a good thing, as this lack of enforcement could be a nightmare in a large swing projects - you could easily spend days tracing the source of a bug back to a point where a UI operation was being done on the wrong thread, and no warning was being thrown.

    There is one (experimental) VM option that you can pass (-Djavafx.embed.singleThread=true) which merges the Swing and the JavaFX platform threads, so you don't need to do quite so much jumping around between UI threads if you're using both toolkits. Use this in production code at your peril, however.