2015-04-04 169 views
7

我試圖設置從一個線程文本對象的字符串,但它給我這個錯誤:java.lang.IllegalStateException:不在FX應用程序線程上; currentThread =線程4

Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4 
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source) 
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source) 
at javafx.scene.Scene.addToDirtyList(Unknown Source) 
at javafx.scene.Node.addToSceneDirtyList(Unknown Source) 
at javafx.scene.Node.impl_markDirty(Unknown Source) 
at javafx.scene.shape.Shape.impl_markDirty(Unknown Source) 
at javafx.scene.Node.impl_geomChanged(Unknown Source) 
at javafx.scene.text.Text.impl_geomChanged(Unknown Source) 
at javafx.scene.text.Text.needsTextLayout(Unknown Source) 
at javafx.scene.text.Text.needsFullTextLayout(Unknown Source) 
at javafx.scene.text.Text.access$200(Unknown Source) 
at javafx.scene.text.Text$2.invalidated(Unknown Source) 
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source) 
at javafx.beans.property.StringPropertyBase.set(Unknown Source) 
at javafx.beans.property.StringPropertyBase.set(Unknown Source) 
at javafx.scene.text.Text.setText(Unknown Source) 
at uy.com.vincent.fx.handling.TableController$1.run(TableController.java:70) 

處理器類:

@FXML 
private Text timer; 

@Override 
public void initialize(URL url, ResourceBundle rb) { 
    init(); 
    new Thread() { 
     public void run() { 
      while(true) { 
       Calendar cal = new GregorianCalendar(); 

       int hour = cal.get(cal.HOUR); 
       int minute = cal.get(cal.MINUTE); 
       int second = cal.get(cal.SECOND); 
       int AM_PM = cal.get(cal.AM_PM); 

       String time = hour + "" + minute + "" + second; 
       timer.setText(time); 
      } 
     } 
    }.start(); 
} 

我m以下a tutorial。 本教程中的人沒有使用JavaFX。

我嘗試過使用Platform.runLater(),它確實有效,但它使我的程序崩潰。 我也嘗試在Platform.runLater(new Runnable() { })方法上創建一個Timer,但它給了我和以前一樣的錯誤。

+1

可能重複http://stackoverflow.com/questions/17850191/why-am-i-getting- java-lang-illegalstateexception-on-javafx) – 2015-04-04 17:28:57

+2

'while(true)'是什麼專業人士稱_bad code_。絕對_never_使用它,至少在循環頭中檢查一個'volatile boolean' – specializt 2015-04-04 20:00:57

回答

15

Wrap timer.setText() in Platform.runLater()。在它之外,在while循環中,添加Thread.sleep(1000);

非法狀態異常背後的原因是您嘗試更新除JavaFX應用程序線程以外的某個線程上的UI。

當你添加它時,你的應用程序崩潰的原因是你通過添加一個要在UI線程上無限執行的進程來重載UI線程。讓線程睡眠1000毫秒可以幫助你解決這個問題。

如果可能,用Timer或TimerTask替換while(true)。

更多的選擇遵循this link

的[爲什麼我對JavaFX的越來越java.lang.IllegalStateException?](
相關問題