[英]Modifying JavaFX gui from different thread in different class
我正在尝试创建一个环境,在该环境中设置一个GUI,并且当用户通过侦听器修改其组件时,另一个线程每X秒向其添加一个新元素。 (是游戏,是的)
我希望游戏在一个类中,而“ element adder”线程在另一个类中,但是Java抱怨我不能从另一个线程修改JavaFX GUI。
我已经看到了使用Platform.runLater()的解决方案,但据我所知,所有这些解决方案都使用匿名内部类。 我真的希望我的加法器位于另一个(命名的)类中。
任何提示将不胜感激,这是代码的最小版本,它再现了该问题:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class DifferentThreadJavaFXMinimal extends Application {
private Thread t;
private GridPane gp;
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
gp = new GridPane();
Scene gameScene = new Scene(gp, 600,500);
primaryStage.setScene(gameScene);
t = new Thread(new Thread2(instance()));
primaryStage.show();
t.start();
}
void addElement(int i) {
Button actualButton = new Button("TEST");
gp.add(actualButton,i,i);
}
public DifferentThreadJavaFXMinimal instance(){
return this;
}
}
class Thread2 implements Runnable {
private DifferentThreadJavaFXMinimal d;
Thread2(DifferentThreadJavaFXMinimal dt){
d=dt;
}
@Override
public void run() {
for (int i=0;i<4;i++) {
d.addElement(i);
}
}
}
您仍然可以使用独立类。
规则是,对UI的更改必须在FX Application线程上进行。 您可以通过包装来自其他线程的调用Platform.runLater(...)
使传递给Platform.runLater(...)
Runnable
的UI发生更改)来使这种情况发生。
在示例代码中, d.addElement(i)
更改UI,因此您将执行以下操作:
class Thread2 implements Runnable {
private DifferentThreadJavaFXMinimal d;
Thread2(DifferentThreadJavaFXMinimal dt){
d=dt;
}
@Override
public void run() {
for (int i=0;i<4;i++) {
final int value = i ;
Platform.runLater(() -> d.addElement(value));
// presumably in real life some kind of blocking code here....
}
System.out.println("Hahó");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.