我的定时器任务中有两个控件:
@FXML TextArea Display;
@FXML Label Label_Display;
执行下方代码会抛出:Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
Timer_task1 = new Timer();
Timer_task1.schedule(new TimerTask(){
int count = 0;
@Override
public void run(){
if (TCP_IP_IsConnect){
count += 1;
System.out.println("Timer1!" + count);
Label_Display.setText(String.format("count=%s", count));//出错之处:Not on FX application thread; currentThread = Timer-0
Display.setText(String.format("count=%s", count));
//JOptionPane.showMessageDialog(null, "警告提示框"+count, "Title", JOptionPane.WARNING_MESSAGE);
}
}
},0,500);
让人百思不得解的是,这俩都是控件,为什么注释掉上面代码中的
Label_Display.setText(String.format("count=%s", count));
他就正常了呢?这不都是控件吗?
没关系,问题还是可以解的,参考这里:https://stackoverflow.com/questions/26916640/javafx-not-on-fx-application-thread-when-using-timer
按他的办法,更改为以下代码后,两个控件都可以使用了,难道这就是C#里面的那个this.Invoke吗?使用委托来解决跨线程。
Timer_task1 = new Timer();
Timer_task1.scheduleAtFixedRate(new TimerTask(){
int count = 0;
@Override
public void run(){
Platform.runLater(() ->{
if (TCP_IP_IsConnect){
count += 1;
System.out.println("Timer1!" + count);
Label_Display.setText(String.format("count=%s", count));
Display.setText(String.format("count=%s", count));
//JOptionPane.showMessageDialog(null, "警告提示框"+count, "Title", JOptionPane.WARNING_MESSAGE);
}
});
}
},0,500);