以下是代码 封装样本;
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/