JavaFx2 IllegalStateException with Label.setText

2019-02-19 10:43发布

问题:

Why when i use a simple Thread like this :

Thread t = new Thread(new Runnable() {
public void run(){
while(true){
  .....
 idLabel.setText(Date.toString);
 Thread.sleep(1000);`
}
t.start(); 

i got this Error :

java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

but if i use an input text (like idInputText) and not a label i didn't have the error ??

回答1:

All UI operation for JavaFX should be performed on FX application thread. You are creating a new Thread t which is not a FX application thread. Hence the exception message:

java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

You need to use Platform#runLater() method for such operations, like as following:

while(true){
    .....
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            idLabel.setText(Date.toString);
        }
    });
    Thread.sleep(1000);`
}