24

Is it possible in javafx to open new stages (windows) from another fxml with a button? Thanks for the answers.

Damien
  • 1,161
  • 2
  • 19
  • 31
Sevi
  • 605
  • 1
  • 6
  • 13

2 Answers2

53

Use the code below on button click:

try {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Demo.fxml"));
    Parent root1 = (Parent) fxmlLoader.load();
    Stage stage = new Stage();
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.initStyle(StageStyle.UNDECORATED);
    stage.setTitle("ABC");
    stage.setScene(new Scene(root1));  
    stage.show();
}
Andrew
  • 26,706
  • 9
  • 85
  • 101
SimplyMe
  • 989
  • 10
  • 14
  • Thank you it works this code, but I'd like a window can be moved separately and close top right corner. – Sevi Nov 27 '14 at 16:33
  • To move and close window comment line with style: StageStyle.UNDECORATED – Serafins Jun 29 '15 at 18:13
  • 1
    It's also a good idea to add `stage.onCloseRequestProperty().setValue(e -> Platform.exit());` to the starting window's stage in order to exit the application closing all the other windows on pressing it's close button. – vivanov Dec 12 '18 at 22:20
25

I had to modify the code a bit and it works fine. Thank you again for the code!

public void pressButton(ActionEvent event) throws Exception {               
    try {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/A.fxml"));
        Parent root1 = (Parent) fxmlLoader.load();
        Stage stage = new Stage();
        stage.setScene(new Scene(root1));  
        stage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
}
Pochmurnik
  • 780
  • 6
  • 18
  • 35
Sevi
  • 605
  • 1
  • 6
  • 13