简体   繁体   English

在 JavaFX 和 Scene Builder 中,单击按钮时如何打开新窗口?

[英]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.我已经获得了第二个窗口的 F​​XML 文件,但我从这里迷路了。 How do I get my program to open the new window and FXML after I press a button?按下按钮后,如何让程序打开新窗口和 FXML?

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.如果您使用 FXML,按钮上有一个名为 onAction 的属性。 You can find it on the "Code" section in scene builder, or directly on the .fxml file.您可以在场景构建器的“代码”部分找到它,或直接在 .fxml 文件中找到它。 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.如果您还没有为场景创建控制器,您只需在场景的根元素中设置属性“控制器”,就像您对按钮的 onAction 所做的那样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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