In JavaFX & Scene Builder, how do I open a new window when clicking a button?


Question

I've already got the FXML file for the second window, and I'm lost from here. How do I get my program to open the new window and FXML after I press a button?

This is how I have my first window set up

@Override 
public void start(Stage primaryStage) throws Exception { 
    Parent root = FXMLLoader.load(getClass().getResource("Main.fxml")); 
    Scene scene = new Scene(root); primaryStage.setResizable(false);    
    primaryStage.setScene(scene); 
    primaryStage.setTitle("Hello World!"); 
    primaryStage.show(); 
} 

So I could copy that but change the values for my new window? Then how would I link that for my button? I've tried some Event handlers but to no avail.

1
0
5/17/2014 2:52:48 AM

If you are using FXML, on the button there is a property called onAction. You can find it on the "Code" section in scene builder, or directly on the .fxml file. There you just type the name of a method.

Then, you need to create this method in the controller class of your scene. If you have not created a controller for your scene, you just need to set the property "controller" in your scene's root element, just like you did with the onAction of the button.

In the method you have created, you just type the code to open the new scene, something like this:

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/org/yourcompanyname/yourapplicationname/layouts/nameOfYourFxmlFile.fxml"));
Parent root = fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setOpacity(1);
stage.setTitle("My New Stage Title");
stage.setScene(new Scene(root, 450, 450));
stage.showAndWait();
0
5/19/2014 3:30:55 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon