[java] close fxml window by code, javafx

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!

This question is related to java user-interface javafx fxml

The answer is


I found a nice solution which does not need an event to be triggered:

@FXML
private Button cancelButton;

close(new Event(cancelButton, stage, null));

@FXML
private void close(Event event) {
    ((Node)(event.getSource())).getScene().getWindow().hide();                      
}

Hide doesn't close the window, just put in visible mode. The best solution was:

@FXML
private void exitButtonOnAction(ActionEvent event){
        ((Stage)(((Button)event.getSource()).getScene().getWindow())).close();      
}

I'm not sure if this is the best way (or if it works), but you could try:

private void on_btnClose_clicked(ActionEvent actionEvent) {

        Window window = getScene().getWindow();   

        if (window instanceof Stage){
            ((Stage) window).close();
        }
}

(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)


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

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent we) {                        
        Platform.setImplicitExit(false);
        stage.close();
    }
});

It is equivalent to hide. So when you are going to open it next time, you just check if the stage object is exited or not. If it is exited, you just show() i.e. (stage.show()) call. Otherwise, you have to start the stage.


finally, I found a solution

 Window window =   ((Node)(event.getSource())).getScene().getWindow(); 
            if (window instanceof Stage){
                ((Stage) window).close();
            }

I implemented this in the following way after receiving a NullPointerException from the accepted answer.

In my FXML:

<Button onMouseClicked="#onMouseClickedCancelBtn" text="Cancel">

In my Controller class:

@FXML public void onMouseClickedCancelBtn(InputEvent e) {
    final Node source = (Node) e.getSource();
    final Stage stage = (Stage) source.getScene().getWindow();
    stage.close();
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to user-interface

Calling another method java GUI How do I center text vertically and horizontally in Flutter? Is it possible to put a ConstraintLayout inside a ScrollView? How to change color of the back arrow in the new material theme? How to create RecyclerView with multiple view type? Android RecyclerView addition & removal of items tkinter: how to use after method Presenting a UIAlertController properly on an iPad using iOS 8 Android ViewPager with bottom dots How do I get the height and width of the Android Navigation Bar programmatically?

Examples related to javafx

IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 JavaFX FXML controller - constructor vs initialize method Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)? cannot resolve symbol javafx.application in IntelliJ Idea IDE javac: invalid target release: 1.8 How to change the color of text in javafx TextField? Issue with background color in JavaFX 8 What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux? How to create a popup windows in javafx

Examples related to fxml

How can I show an image using the ImageView component in javafx and fxml? JavaFX Panel inside Panel auto resizing Passing Parameters JavaFX FXML close fxml window by code, javafx JavaFX 2.1 TableView refresh items