How to implement the close button event on a screen?

1

When I create a screen in the Scene Builder in JavaFX, three buttons in the upper corner of the screen are as default: minimize , maximize , and close .

My question

How can I manipulate and implement the click event of the close (X) button, so that when the user clicks close I execute some action or method?

    
asked by anonymous 22.06.2016 / 19:39

2 answers

1

Do the following:

public class SuaClasse extends Application {
    public void start(Stage tela) throws IOException {        
        tela.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent t) {
                t.consume();

                // Coloque aqui o código a ser executado ao fechar o sistema.

                tela.close();
                Platform.exit();
                System.exit(0);
            }
        });
    }
}
    
07.07.2016 / 03:59
0

Give the button: <Button fx:id="fecharTela" onAction="#closeButtonAction">

In your class that controls Scene, add the following code:

@FXML private javafx.scene.control.Button fecharTela;

@FXML
private void fecharTelaAction(){
    Stage stage = (Stage) fecharTela.getScene().getWindow(); //Obtendo a janela atual
    stage.close(); //Fechando o Stage
}
    
26.05.2017 / 18:10