Yes it is possible. You need to use the enterNestedEventLoop and exitNestedEventLoop methods (they are inside the class com.sun.javafx.tk.Toolkit). See this usage example:
// Make sure to import the FX Toolkit first import com.sun.javafx.tk.Toolkit; // This object will be used as a unique identifier to the nested loop (to // block the execution of the thread until exitNestedEventLoop is called) final Object loopLock = new Object(); // Simulate a long process thread (DB call, download, etc) Thread longProcess = new Thread(new Runnable() { @Override public void run() { // Sleep for 12 seconds to simulate a long process try { Thread.sleep(12000); } catch (InterruptedException e) { e.printStackTrace(); } // Setup a result to pass back to the enterNestedLoop() caller String result = "Result of this long process"; // We are now done. Call exitNestedEventLoop() to unblock // the enterNestedLoop() caller. This needs to run from // the FX Thread so use Platform.runLater() Runnable fxRunner = new Runnable() { public void run() { try { Toolkit.getToolkit().exitNestedEventLoop(loopLock, result); } catch (Throwable t) { t.printStackTrace(); } } }; Platform.runLater(fxRunner); } }); // Start that long process from the FX Thread longProcess.start(); // The next call will block until exitNestedEventLoop is called, however // the FX Thread will continue processing UI requests Object result = Toolkit.getToolkit().enterNestedEventLoop(loopLock); // Next statement will print: "Result of this long process" System.out.println("Result is: " + result);
Now, before using this, you will be warned about two important things :
The com.sun.javafx.tk.Toolkit class is not part of the public API, so Oracle reserves the right to remove it without notice. I use it just fine from Java 7 to 8u51 so that they can stay there forever, change the package / names or completely disappear (unlikely).
Nested loops (and secondary Swing loops) are great for flexibility and small applications, but their overuse is often price-related. Embedding in a lot of loops (huge stack trace) often leads to “weird” behavior in your applications, as the source parts of your code may be waiting for four or five things that are completely unrelated to them. I saw FX nested loops causing “empty” exceptions in FX WebEngine executeScript () calls and duplicating keyboard preprocessing (when pairing FX + Swing) among other problems.
I would recommend using javafx.concurrent.Task (if that makes sense). Using the Task class will require a little bit of effort, but I believe that this is the right way to do things and will probably save you a lot of maintenance time.
For more help on the FX action class, see this great article: http://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
UPDATE: enterNestedEventLoop and exitNestedEventLoop will be part of the Java 9 public API (platform class), more information in JDK-8090865
Hope this helps!
source share