Spring Boot JavaFX starter
為了方便的將Spring boot 與 JavaFX結(jié)合,可以方便的在JavaFx中使用Spring boot的能力份乒,自己寫個(gè)包發(fā)布到中央倉庫
Maven
添加以下依賴
<dependency>
<groupId>io.github.podigua</groupId>
<artifactId>javafx-podigua-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
用法
創(chuàng)建一個(gè)類,繼承AbstractJavafxApplication
,然后調(diào)用launch
方法啟動(dòng)JavaFX
程序
用法1
使用普通方法啟動(dòng)界面
@SpringBootApplication
public class TestApplication extends AbstractJavafxApplication {
public static void main(String[] args) {
launch(TestApplication.class, args);
}
@Override
protected void ready(Stage stage) {
VBox root = new VBox();
Button button = new Button("測(cè)試");
button.setOnAction(event -> {
Alert alert = new Alert(AlertType.NONE, "點(diǎn)擊了按鈕", ButtonType.OK);
alert.showAndWait();
});
root.getChildren().add(button);
Scene scene = new Scene(root, 1000, 750);
stage.setScene(scene);
stage.show();
}
}
用法2
使用Fxml啟動(dòng)界面
啟動(dòng)類
FxmlService
封裝了加載fxml
文件的方法,并獲取spring
容器中的對(duì)應(yīng)的bean
需要在fxml文件中聲明fx:controller
@SpringBootApplication
public class TestApplication extends AbstractJavafxApplication {
public static void main(String[] args) {
launch(TestApplication.class, args);
}
@Autowired
private FxmlService fxmlService;
@Override
protected void ready(Stage stage) {
Parent parent = fxmlService.load("fxml/index.fxml");
stage.setScene(new Scene(parent, 1000, 750));
stage.show();
}
}
fxml
路徑為:fxml/index.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.IndexController"
prefHeight="400.0" prefWidth="600.0">
<Button text="測(cè)試" onAction="#test"></Button>
</AnchorPane>
controller
controller
需要添加@Service
使controller
注冊(cè)為spring
的bean
@Service
public class IndexController implements Initializable {
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("initialize");
}
public void test(ActionEvent event) {
Alert alert = new Alert(AlertType.NONE, "點(diǎn)擊了按鈕", ButtonType.OK);
alert.showAndWait();
}
}
動(dòng)畫
spring boot 加載過程較慢,spring加載過程中會(huì)展示一個(gè)動(dòng)畫,動(dòng)畫默認(rèn)由DefaultSplashScreen
提供,默認(rèn)可見
創(chuàng)建一個(gè)類實(shí)現(xiàn)SplashScreen
可以修改是否可見,以及圖片的選擇,若不以圖片的方式展示,可以自行定義getParent
方法
public class ImageSplashScreen implements SplashScreen {
@Override
public boolean visible() {
return true;
}
@Override
public String getImagePath() {
return "start.png";
}
}
啟動(dòng)類調(diào)用launch
的重載方法
@SpringBootApplication
public class TestApplication extends AbstractJavafxApplication {
public static void main(String[] args) {
launch(TestApplication.class, new ImageSplashScreen(), args);
}
@Autowired
private FxmlService fxmlService;
@Override
protected void ready(Stage stage) {
Parent parent = fxmlService.load("fxml/index.fxml");
stage.setScene(new Scene(parent, 1000, 750));
stage.show();
}
}