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!
@ZinMinn if you want to close the app, just call Platform. exit(). Closing a stage is different than closing the app (you can have multiple stages). This solution is perfect to close a secondary window.
Be default, to quit the program is to let the user click the standard window close button, typically represented by an X in the upper-right corner of the window's title bar.
It's generally recommended that you exit a JavaFX Application with a call to Platform. exit() , which allows for a graceful shutdown: for example if there is any "cleanup" code you need, you can put it in the stop() method and Platform. exit() will allow it to be executed.
<Button fx:id="closeButton" onAction="#closeButtonAction"> 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(); }  If you have a window which extends javafx.application.Application; you can use the following method. (This will close the whole application, not just the window. I misinterpreted the OP, thanks to the commenters for pointing it out).
Platform.exit();   Example:
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();   } }   Edit for the beauty of Java 8:
 public class MainGUI extends Application {     .........      Button exitButton = new Button("Exit");     exitButton.setOnAction(actionEvent -> Platform.exit());  } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With