I need to close the current fxml window by code in the controller

I know stage.close() or stage.hide() do this in fx

how to implement this in fxml? I tried

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

}

but it doesn't work!

All help will be greatly appreciated. Thanks!

解决方案

give your close button an fx:id, if you haven't yet:

In your controller class:

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

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐