[英]How to make thread A change scene in JavaFX thread B if A was launched by B?
我正在嘗試制作JavaFX游戲。 有一個主線程(B)在onMouseReleased的另一個線程(A)中啟動一些物理計算。 線程A計算所需的移動並使圖形在屏幕上移動。 停球后,應更改場景以顯示結果,並讓用戶重新啟動級別或走得更遠。
如果在B中使用join()等待A完成,然后更新場景,則在執行A中的計算時B不會響應,並且不會顯示圖形的移動。 這是不可接受的。
如果試圖從A更改應用場景,我會得到
java.lang.IllegalStateException:不在FX應用程序線程上
使賽后畫面出現時我應該意識到什么概念?
這是線程A的結構:
class Physics implements Runnable{
private Ball ball;
private Pane game;
private Thread t;
private boolean paused;
Physics(Pane game, Ball ball){
super();
this.ball=ball;
this.game=game;
this.paused=true;
t=new Thread(this);
}
public void run(){
this.unPause();
while(ball.getXSpeed()!=0||ball.getYSpeed()!=0){
try {
sleep(20);
}
catch (InterruptedException ex){
ball.stop();
}
if(!paused) {
ball.step();
interactGravities();
checkObstacles();
checkTargets();
checkEdges();
}
}
Main.showResult();
}
}
每個checkObstacles,checkTargets,checkEdges都可以使ball.stop()結束while循環。 Main.showResult()是嘗試在線程B中設置setScene()但獲取java.lang.IllegalStateException的方法。
您應該使用Platform.runLater()。 此命令強制從JavaFx線程中的Runnable(在Platform.runLater方法的參數中獲取)執行提供的任務。 使用setScene命令或其他可在Runnable內部操作場景的函數。
PS可運行對象也可以在Java8中表示為Lambda表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.