import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class MainApp extends Application {
private static ConfigurableApplicationContext springContext;
@Override
public void init() throws Exception {
springContext = SpringApplication.run(MainApp.class);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/main.fxml"));
AnchorPane root = loader.load();
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
}
@Override
public void stop() throws Exception {
springContext.close();
}
public static void main(String[] args) {
launch(args);
}
}这段代码展示了如何在SpringBoot应用中整合JavaFX来进行桌面应用开发。在MainApp类中,我们继承了Application类并重写了init、start和stop方法。init方法中启动了Spring应用上下文,start方法中使用JavaFX加载并显示了一个FXML文件,stop方法中关闭了Spring应用上下文。最后,通过main方法启动了JavaFX应用。