有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java更新场景和线程

我试图让一个场景逐步显示我在线程中定期更新的类实例所做的更改

到目前为止我有

 public void start(Stage primaryStage) {   
    Environment env = new Environment(10, 10);
    StackPane layout = new StackPane();

    primaryStage.setTitle("Vacuum World");
    Button btn = new Button();
    btn.setText("Start");

    Text text = new Text();

    btn.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent event) {
            Thread t = new updateThread(env, text);
            t.run();
        }
    });

    layout.getChildren().add(btn);
    layout.getChildren().add(text); 
    primaryStage.setScene(new Scene(layout));
    primaryStage.show();
}

而问题的线索是:

public class updateThread extends Thread {
    Environment env;
    Text text;

    public updateThread(Environment env, Text text) {
        this.env = env;
        this.text = text;
    }

    public void run() {
        int updatesPerSecond = 2;
        int nbUpdates = 0;
        int targetTime = 1000 / updatesPerSecond;
        long currentTime;
        long lastTime = System.nanoTime();
        long elapsedTime;
        long sleepTime;

        while (nbUpdates < 10) {
            currentTime = System.nanoTime();

            elapsedTime = currentTime - lastTime;
            lastTime = currentTime;

            this.env.update();
            text.setText(this.env.show());

            nbUpdates++;
            sleepTime = targetTime - (elapsedTime / 1000000000);

            if (sleepTime < 0) {
                sleepTime = 1;
            }

            try {
                Thread.sleep(sleepTime);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

我最终得到的结果是,在按下按钮后,线程运行并正确更新环境,但场景仅在线程运行完成后更改一次,而在线程运行时不会更新。你知道如何得到我想要的结果吗


共 (1) 个答案

  1. # 1 楼答案

    调用Thread.run,它在当前线程上运行Threadrun方法。您需要使用Thread.start来创建一个新线程

    此外,应该使用Platform.runLater从不同线程进行更新:

    ...
    this.env.update();
    final String newText = this.env.show();
    Platform.runLater(() -> text.setText(newText))
    ...
    

    还要注意,纳秒是10^-9秒=10^-6毫秒。你应该除以1_000_000而不是1_000_000_000,并且可能在环境/UI更新之后进行计时,因为这可能也需要一些时间