How to implement a close (close) screen event?

Asked

Viewed 6,513 times

1

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

My question

How I can manipulate and implement the button click event close-up (X), so that when the user clicks on close I would perform some action or method?

  • 1

    I don’t mean to be boring, but you could elaborate on the questions, so they don’t look vague. For example, adding an example you’ve already done or tried. Again, I found a example in SOEN, see if you can adapt.

  • In this example was created a button where I click to close the Stage, I would like to know some method able to identify when the user clicked the close button in the upper corner of the screen what is already default when creating a screen in the Scene Builder !

  • @diegofm edited his question. Bruno see if my edition left the question clearer according to what you want?

  • Yes, thank you very much !

  • @drmcarvalho turned out great!

  • Bruno, look at some of these answers of this link.

  • @Bruno you can create the question normally, but avoid erasing and recreating the same always, this can be seen badly. Read on [Ask] to elaborate a question that is easy to understand and so get an answer. And be patient, sometimes it takes someone a while to answer.

  • @Bruno, you’ve already done it?

Show 3 more comments

2 answers

1

Give an id to 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
}
  • Velasco, Thank you! was with the same doubt, his answer was simple and objective.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.