使用FXML的JavaFX Window Changer [英] JavaFX Window Changer using FXML

查看:153
本文介绍了使用FXML的JavaFX Window Changer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在单击按钮时创建一个Window(场景)转换器。具体来说,在登录用户时更改窗口。我想知道如何减少冗余代码,并将负责更改窗口的方法置于集中的位置。是否有特定的设计模式?

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

谢谢!

推荐答案

对于动态变化的阶段,你可以(我目前正在使用这种方法)拥有一个AnchorPane。比如说,你的根上面有一个AnchorPane。您可以使用此窗格更改场景。
首先,在你的控制器中声明AnchorPane:

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

然后一切都完成了,现在你可以通过简单地调用它来改变你的场景在按钮的ActionEvent中,如下所示,

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

这就是全部!

这篇关于使用FXML的JavaFX Window Changer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆