gpt4 book ai didi

JavaFX:动态更改舞台标题

转载 作者:行者123 更新时间:2023-12-01 18:04:09 25 4
gpt4 key购买 nike

以下是代码 封装样本;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

Scene scene = new Scene(root);
primaryStage.setTitle("Change me");

primaryStage.setScene(scene);
primaryStage.show();

for(long i=0;i<3;i++){
primaryStage.setTitle("Change title to "+i);
try{
Thread.sleep(1000);
}
catch (Exception e){
e.printStackTrace();
}
}
}

}

目的是启动窗口,然后更改标题,但发生的情况是首先执行循环,然后显示窗口。

最佳答案

除了 this ,使用普通线程进行计算并使用 JavaFX 线程(即 Platform.runlater())进行 UI 更新是另一种解决方案。

使用this教程,我能够完成任务。原因直接引用教程中的——

It is repeated to emphasize that all UI event handlers in JavaFX run on a single thread, which is the JavaFX Application Thread.

新代码是

package sample;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main extends Application {

public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

Scene scene = new Scene(root);
primaryStage.setTitle("Change me");

primaryStage.setScene(scene);
primaryStage.show();
System.out.println("shown");
Thread thread = new Thread(){
public void run(){
for (long i = 0; i < 6; i++) {
long finalI = i;
Platform.runLater(()-> {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
primaryStage.setTitle("Change title to " + finalI);
});
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
thread.start();
}

}

关于JavaFX:动态更改舞台标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60585476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com