JavaFX之切換界面視圖(springboot)


前言:JavaFX啓動後,如何進行界面的切換呢?,我們接着本專欄的demo進行演示

一:創建另一個視圖Main

main.fxml

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="com.xiyang.boot.controller.MainController"
            prefHeight="400.0" prefWidth="600.0" style="-fx-border-color: red;-fx-border-width: 1">
    <Button AnchorPane.topAnchor="100" text="你好"/>
</AnchorPane>

MainView

@FXMLView(value = "/fxml/main.fxml")
public class MainView extends AbstractFxmlView {
}

MainController

@FXMLController
public class MainController {
}

二:編寫界面切換事件

界面切換在我看來有兩種:

  1. 給定一個容器,替換其中的node
@FXMLController
public class LoginController implements Initializable {
    public Button button;
    public VBox vbox;
    @Autowired
    private MainView mainView;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        button.setOnAction(event -> {
            vbox.getChildren().addAll(mainView.getView());
            GUIState.getStage().setWidth(600);
            // 將舞臺置於窗口中央
            GUIState.getStage().centerOnScreen();
        });
    }
}

效果
在這裏插入圖片描述
2. 替換場景(scene)
如springboot-javafx-support的showView源碼

    public static void showView(final Class<? extends AbstractFxmlView> newView) {
        try {
            final AbstractFxmlView view = applicationContext.getBean(newView);

            if (GUIState.getScene() == null) {
                GUIState.setScene(new Scene(view.getView()));
            } else {
                GUIState.getScene().setRoot(view.getView());
            }
            GUIState.getStage().setScene(GUIState.getScene());

            applyEnvPropsToView();

            GUIState.getStage().getIcons().addAll(icons);
            GUIState.getStage().show();

        } catch (Throwable t) {
            LOGGER.error("Failed to load application: ", t);
            showErrorAlert(t);
        }
    }

保持當前單例舞臺,只是替換場景
修改MainController

@FXMLController
public class LoginController implements Initializable {

    public Button button;
    public VBox vbox;

    @Autowired
    private MainView mainView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        button.setOnAction(event -> {
//            vbox.getChildren().addAll(mainView.getView());
//            GUIState.getStage().setWidth(600);
//            // 將舞臺置於窗口中央
//            GUIState.getStage().centerOnScreen();
            JavafxSpringboot4Application.showView(MainView.class);

        });
    }
}

效果
在這裏插入圖片描述

注意:不管你是否結合springboot,都應只用一個stage來保存場景,
界面切換時,也不建議關閉當前stage,再取開啓另一個stage,這樣耗費了性能

三:demo地址

demo地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章