How to close a java window with a button click - JavaFX Project


I made a JavaFX project and created the GUI for the first-login frame in the java Scene Builder. When the login is successful, the login frame must be closed and the next frame must be visible (main program frame). I can make the new frame appear, but I can't make the login frame closed. I tried stuff like dispose() but nothing works. Below is the code for the main class:

public class KuberComm extends Application {

    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);
        stage.setTitle("Login to KuberComm");

     * @param args the command line arguments
    public static void main(String[] args) {


The handler for the login button is located in another class (controller class made by the NetBeans IDE). I can't figure out what the frame's name is in order to use it in the controller class.

Any help will be much appreciated!

8/19/2016 1:51:43 PM

give your button a name in the controller class:

public Button closeButton;

and add this method:

public void handleCloseButtonAction(ActionEvent event) {
    Stage stage = (Stage) closeButton.getScene().getWindow();

In your FXML you need a reference to the button name and the method to call onAction:

<Button fx:id="closeButton" cancelButton="true" layoutX="350.0" layoutY="767.0" mnemonicParsing="false" onAction="#handleCloseButtonAction" prefWidth="100.0" text="Close" />

This would close the stage that this button is on.

7/30/2014 1:42:59 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow