通过代码关闭 fxml 窗口,javafx

新手上路,请多包涵

我需要通过控制器中的代码关闭当前的 fxml 窗口

我知道 stage.close() 或 stage.hide() 在 fx 中执行此操作

如何在 fxml 中实现这个?我试过了

private void on_btnClose_clicked(ActionEvent actionEvent) {
        Parent root = FXMLLoader.load(getClass().getResource("currentWindow.fxml"));
        Scene scene = new Scene(root);

        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();
}

但它不起作用!

所有帮助将不胜感激。谢谢!

原文由 alfredo138923 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 487
2 个回答
  1. 给你的关闭按钮一个 fx:id,如果你还没有: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. 在您的控制器类中:
    @FXML private javafx.scene.control.Button closeButton;

   @FXML
   private void closeButtonAction(){
       // get a handle to the stage
       Stage stage = (Stage) closeButton.getScene().getWindow();
       // do what you have to do
       stage.close();
   }

原文由 a.b 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您有一个扩展窗口 javafx.application.Application; 您可以使用以下方法。 (这将关闭整个应用程序,而不仅仅是窗口。我误解了 OP,感谢评论者指出)。

 Platform.exit();

例子:

 public class MainGUI extends Application {
.........

Button exitButton = new Button("Exit");
exitButton.setOnAction(new ExitButtonListener());
.........

public class ExitButtonListener implements EventHandler<ActionEvent> {

  @Override
  public void handle(ActionEvent arg0) {
    Platform.exit();
  }
}

为 Java 8 之美而编辑:

  public class MainGUI extends Application {
    .........

    Button exitButton = new Button("Exit");
    exitButton.setOnAction(actionEvent -> Platform.exit());
 }

原文由 codepleb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题