java - Why JavaFX requires Platform.runLater to change anything in it's UI inside a thread? -


this code of simple swing application:

final jframe jframe = new jframe(); final jlabel jlabel = new jlabel("test"); jframe.add(jlabel); jframe.setdefaultcloseoperation(jframe.exit_on_close); jframe.pack(); jframe.setlocationrelativeto(null); jframe.setvisible(true);  thread thread = new thread(){     @override     public void run() {         while(true) {             jlabel.settext("time: " + system.currenttimemillis());             try { thread.sleep(1000);} catch(exception ex) {}         }     } }; thread.setdaemon(true); thread.start(); 

runs expected. if same javafx, error java.lang.illegalstateexception: not on fx application thread when setting text label.

i want know, why has this? why can't have freedom whant, when want?

because javafx single threaded, ui toolkits.

your swing code broken - swing single threaded, , should execute jlabel.settext(...) on awt event handling thread, either wrapping in swingutilities.runlater(...);, or using higher-level api such timer. may happen run expected on particular system, particular jdk implementation, coding contrary contract of toolkit using, , there no guarantee going work on other jdk implementations or other platforms.

one major improvement of javafx on swing javafx enforces threading rules as possible throwing illegalstateexception when threading wrong. in swing, code prone random, unpredictable failure @ point in future, no warning @ all.

there cases javafx not enforce rules, presumably because adversely affect performance relevant checking, should still follow contract: changes ui must performed on ui thread.

as why javafx, swing, , other ui toolkits written this: complex question. part, ui programming event driven; of time code write modifies scene graph in response user event; i.e. ui thread natural place modifying ui anyway. because of this, effort , performance hit come making ui toolkit thread safe not worthwhile. nevertheless, attempts have been made write thread-safe ui toolkits, they've never worked well: added burden of synchronization adversely affects performance degree renders them unusable. outside scope of understanding, i've read problem layout typically done in opposite direction event handling (i.e. window down recursively down child components, versus "leaf" components via parents window). while it's feasible handle synchronization either layout or event handling, becomes prohibitively expensive both. see this (probably more accurate) discussion.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -