目录

  • 一:创建另一个视图Main
  • 二:编写界面切换事件
  • 三:demo地址



前言: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();
        });
    }
}

效果

java fx 窗口跳转 javafx实现页面切换_spring


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);

        });
    }
}

效果

java fx 窗口跳转 javafx实现页面切换_spring_02

注意:不管你是否结合springboot,都应只用一个stage来保存场景,
界面切换时,也不建议关闭当前stage,再取开启另一个stage,这样耗费了性能

三:demo地址

demo地址