Update your Scene in JavaFX
February 9, 2014 12 Comments
Usually it is very simple to update your scene in JavaFX. For example if you want to update the X and Y position of your nodes, you can often simply do some stuff like:
node.setLayoutX(100d); node.setLayoutY(150d);
But this isn’t a good way of doing it. In JavaFX you have to be sure you are in the JavaFX application thread. But how can you know this?
Platform.isApplicationFxThread();
But what if you’re not in that thread?
Platform.runLater(Runnable r);
So each time you would like to update your scene manually, you should check if you’re or not in the FX application thread. So let’s make a really simple helper class:
/** * @author Thierry Wasylczenko */ public class PlatformHelper { public static void run(Runnable treatment) { if(treatment == null) throw new IllegalArgumentException("The treatment to perform can not be null"); if(Platform.isFxApplicationThread()) treatment.run(); else Platform.runLater(treatment); } }
The method run does the check for you. Finally you can use a lambda expression to execute that code:
final Node node = ... ; PlatformHelper.run(() -> { node.setLayoutX(100d); node.setLayoutY(150d); });
That’s it.