JavaFX Window Changer using FXML

 ̄綄美尐妖づ 提交于 2019-12-02 22:29:13

问题


I'm currently attempting to make a Window (Scene) changer when clicking on a button. Specifically, changing the window when logging in a user. I would like to know how I can possibly reduce redundant code, and placing the methods responsible for changing windows in a centralized place. Is there a specific design pattern to follow?

So far, I have this:

Main.java

public class Main extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = (Parent) FXMLLoader.load(getClass().getResource("Login.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add("Styles.css");
        stage.setScene(scene);
        stage.setTitle("App");
        stage.setResizable(false);
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

LoginController.java

public class LoginController implements Initializable {

    @FXML
    private TextField email;
    @FXML
    private PasswordField password;
    @FXML
    private Button buttonLogin;

    private Stage stage;

    @Override
    public void initialize(URL url, ResourceBundle rb) {}    

    @FXML
    private void login(ActionEvent event) throws Exception {
        stage = (Stage) buttonLogin.getScene().getWindow();
        Parent root = (Parent) FXMLLoader.load(getClass().getResource("Profile.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add("Styles.css");
        stage.setScene(scene);
        stage.centerOnScreen();
        stage.show();
    }
}

Thanks!


回答1:


For a dynamically changing stage, you can (I'm currently using this method) have an AnchorPane. Say, there is an AnchorPane on top of your root. You can change the scene using this pane. First, declare the AnchorPane in your controller :

@FXML
AnchorPane dynamicPane;

Then, you should provide a method (a setter specifically), where it would look like,

private void setDynamicPane(AnchorPane dynamicPane){
      this.dynamicPane.getChildren().clear();
      this.dynamicPane.getChildren().add(dynamicPane);
}

Then it's all done, and now you can change you scene by simply calling it in a button's ActionEvent as following,

@FXML
private void yourButtonAction(ActionEvent evt){
    setDynamicPane(FXMLLoader.load(getClass().getResources("path/to/your/file.fxml"));
}

That's all!



来源:https://stackoverflow.com/questions/46985889/javafx-window-changer-using-fxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!