How to open another window in JavaFX 2?

2020-02-10 14:20发布

问题:

I have made a simple JavaFX application, but I would like the main window to open a secondary window when the user clicks a button.

What would be the simplest way to accomplish this?

回答1:

Button b = new Button();
b.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
        Stage stage = new Stage();
        //Fill stage with content
        stage.show();
    }
});


回答2:

try this


try {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("FXML.fxml"));
    Parent root1 = (Parent) fxmlLoader.load();
    Stage stage = new Stage();
    stage.setScene(new Scene(root1));
    stage.show();
    ((Node) (event.getSource())).getScene().getWindow().hide();
} catch (Exception e) {
    e.printStackTrace();
}