Spring Boot JavaFX starter

Spring Boot JavaFX starter

为了方便的将Spring boot 与 JavaFX结合,可以方便的在JavaFx中使用Spring boot的能力,自己写个包发布到中央仓库

Maven

添加以下依赖


    io.github.podigua
    javafx-podigua-boot-starter
    1.0.0

用法

创建一个类,继承AbstractJavafxApplication,然后调用launch方法启动JavaFX程序

用法1

使用普通方法启动界面

@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("测试");
        button.setOnAction(event -> {
            Alert alert = new Alert(AlertType.NONE, "点击了按钮", ButtonType.OK);
            alert.showAndWait();
        });
        root.getChildren().add(button);
        Scene scene = new Scene(root, 1000, 750);
        stage.setScene(scene);
        stage.show();
    }
}

用法2

使用Fxml启动界面

启动类

FxmlService 封装了加载fxml文件的方法,并获取spring容器中的对应的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






    

controller

controller 需要添加@Service使controller注册为springbean


@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, "点击了按钮", ButtonType.OK);
        alert.showAndWait();
    }
}

动画

spring boot 加载过程较慢,spring加载过程中会展示一个动画,动画默认由DefaultSplashScreen提供,默认可见

创建一个类实现SplashScreen可以修改是否可见,以及图片的选择,若不以图片的方式展示,可以自行定义getParent方法

public class ImageSplashScreen implements SplashScreen {

    @Override
    public boolean visible() {
        return true;
    }

    @Override
    public String getImagePath() {
        return "start.png";
    }
}

启动类调用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();
    }
}

你可能感兴趣的:(Spring Boot JavaFX starter)