JavaFX 11 和 Spring Boot 2.0。
我想显示一个启动屏幕,直到 Spring 初始化所有必需的 bean,并且在 spring.run() 中我想关闭启动阶段(或至少在 x 秒后)。这样连接到数据库创建 POJO 等。但是当我尝试在 FX 线程启动之前显示启动屏幕时,它会抛出:
Caused by: java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = main()
我什至在Platform.runLater()
中尝试过,但仍然没有成功。有解决这个问题的方法吗?谢谢。
public class StartUp extends Application{
public static void main(String[] args) {
loadSplashScreen();
appContext = SpringApplication.run(StartUp.class);
launch(args);
}
@Override
public void start(Stage stage) {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
stage.setScene(new Scene(root, 300, 275));
stage.show();
}
static void loadSplashScreen() {
Stage splashStage = new Stage();
try {
BorderPane splashPane = FXMLLoader.load(getClass().getResource("splash.fxml"));
Scene splashScene = new Scene(splashPane);
splashStage.setScene(splashScene);
splashStage.show();
setFadeInOut(splashPane, splashStage);
} catch (IOException e) {
e.printStackTrace();
}
}
static void setFadeInOut(Parent splashScene, Stage splashStage) {
FadeTransition fadeIn = new FadeTransition(Duration.seconds(3), splashScene);
fadeIn.setFromValue(0);
fadeIn.setToValue(1);
fadeIn.setCycleCount(1);
FadeTransition fadeOut = new FadeTransition(Duration.seconds(3), splashScene);
fadeOut.setFromValue(1);
fadeOut.setToValue(0);
fadeOut.setCycleCount(1);
fadeIn.play();
fadeIn.setOnFinished((e) -> fadeOut.play());
fadeOut.setOnFinished((e) -> splashStage.close());
}
}
最佳答案
在您的代码中,您有一个名为 loadSplashScreen()
的方法,您可以在 Application.launch()
之前调用该方法。调用 launch
方法将启动 JavaFX 线程,这就是您的 loadSplashScreen()
方法失败的原因,即调用此方法时 JavaFX 线程甚至还没有启动。
您可能想看一下here在尝试使用 Spring Boot 启动 JavaFX 之前,请阅读有关 PreLoaders 的 Oracle 教程,了解如何理解基本示例。
虽然我没有从 Spring Boot 启动 JavaFX,但我在 OSGi 包中做了类似的事情,您可能想看看我的 FlexFx GitHub 存储库 here这可能会给您一些关于如何在 Spring Boot 中使用预加载器的提示,但请注意,我目前无法在我的项目中显示启动屏幕。
最后,您的问题会发生在 JavaFX-8、9 或 10 上。这不是 JavaFX-11 所特有的。
关于带 Spring Boot 的 Javafx 启动屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54009386/