简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM