11

我需要一种Stage通过单击从内部关闭 a 的方法 a Button

我有一个主类,我从中创建一个带有场景的主舞台。我为此使用 FXML。

public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Builder.fxml"));
    stage.setTitle("Ring of Power - Builder");
    stage.setScene(new Scene(root));
    stage.setMinHeight(600.0);
    stage.setMinWidth(800.0);
    stage.setHeight(600);
    stage.setWidth(800);
    stage.centerOnScreen();
    stage.show();
}

现在在出现的主窗口中,我拥有通​​过 FXML 和适当的控件类制作的所有控件项、菜单和内容。这就是我决定在帮助菜单中包含关于信息的部分。所以当菜单帮助 - 关于被激活时,我有一个事件正在进行,如下所示:

@FXML
private void menuHelpAbout(ActionEvent event) throws IOException{
    Parent root2 = FXMLLoader.load(getClass().getResource("AboutBox.fxml"));
    Stage aboutBox=new Stage();
    aboutBox.setScene(new Scene(root2));
    aboutBox.centerOnScreen();
    aboutBox.setTitle("About Box");
    aboutBox.setResizable(false);
    aboutBox.initModality(Modality.APPLICATION_MODAL); 
    aboutBox.show();
}

正如所见,关于框窗口是通过带有控制器的 FXML 创建的。我想添加一个Button从控制器内关闭新阶段。

我发现自己能够做到这一点的唯一方法是定义一个公共静态 Stage aboutBox;在 Builder.java 类中,并从 AboutBox.java in 方法中引用该类,该方法处理关闭按钮上的操作事件。但不知何故,它感觉并不完全干净和正确。有没有更好的办法?

4

2 回答 2

27

您可以从传递给事件处理程序的事件派生要关闭的阶段。

new EventHandler<ActionEvent>() {
  @Override public void handle(ActionEvent actionEvent) {
    // take some action
    ...
    // close the dialog.
    Node  source = (Node)  actionEvent.getSource(); 
    Stage stage  = (Stage) source.getScene().getWindow();
    stage.close();
  }
}
于 2012-07-13T18:23:55.550 回答
1

在 JavaFX 2.1 中,您几乎没有选择。像珠宝海的答案那样的方式,或者您已经完成的方式或修改版本的方式

public class AboutBox extends Stage {

    public AboutBox() throws Exception {
        initModality(Modality.APPLICATION_MODAL);
        Button btn = new Button("Close");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                close();
            }
        });

        // Load content via
        // EITHER

        Parent root = FXMLLoader.load(getClass().getResource("AboutPage.fxml"));
        setScene(new Scene(VBoxBuilder.create().children(root, btn).build()));

        // OR

        Scene aboutScene = new Scene(VBoxBuilder.create().children(new Text("About me"), btn).alignment(Pos.CENTER).padding(new Insets(10)).build());
        setScene(aboutScene);

        // If your about page is not so complex. no need FXML so its Controller class too.
    }
}

像这样的用法

new AboutBox().show();

在菜单项操作事件处理程序中。

于 2012-07-13T12:10:36.387 回答