建立基於maven的javaFx+springboot項目有兩種方式,第一種爲經過非編碼的方式來設計UI集成springboot;第二種爲分離用戶界面(UI)和後端邏輯集成springboot,其中用戶界面爲fxml文件。java
maven依賴spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>de.roskenet</groupId> <artifactId>springboot-javafx-support</artifactId> <version>${springboot-javafx-support.version}</version> </dependency>
建立StartMain類,並繼承Application後端
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import java.util.Objects; import java.util.function.Consumer; /** * maven構建JavaFX項目啓動類 */ public class StartMain extends Application implements CommandLineRunner, Consumer<Stage> { /** * 窗口啓動接口,原理: * 1. run(String... args)中給springStartMain賦值 * 2. start(Stage primaryStage)中調用了springStartMain來操做primaryStage * 3. 而springStartMain其實是spring管理的StartMain一個對象,所以accept方法中能夠操做spring管理的任何對象 */ private static Consumer<Stage> springStartMain; private final Button btnStart = new Button("開 始"); @Override public void accept(Stage stage) { final GridPane gridPane = new GridPane(); gridPane.setPrefWidth(700); gridPane.setPadding(new Insets(10, 10, 10, 10)); gridPane.setVgap(10); gridPane.setHgap(10); btnStart.setStyle("-fx-padding: 10;-fx-end-margin:20;"); HBox hBox1 = new HBox(); hBox1.getChildren().addAll(btnStart); hBox1.setSpacing(20); gridPane.addRow(2, new Label(), hBox1); //頁面 Group root = new Group(); Scene scene = new Scene(root, 720, 500); scene.setRoot(gridPane); //設置標題 stage.setTitle("Hello World"); //stage的標題將會是hello stage.setScene(scene); stage.show(); } @Override public void start(Stage primaryStage) throws Exception { springStartMain.accept(primaryStage); } @Override public void run(String... args) throws Exception { springStartMain = Objects.requireNonNull(this); } public static void main(String[] args) { //啓動spring-boot SpringApplication.run(StartMain.class, args); //啓動窗口 Application.launch(args); } }
項目結構以下:springboot