vendredi 27 octobre 2017

JavaFX Window Changer using FXML

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!

Aucun commentaire:

Enregistrer un commentaire