Suthar
Suthar

Reputation: 91

How can I call a function at time of closing of JFrame?

As i want to go for backup before the closing of program.
How i can call backup function when user click on (Right corner button of closing that JFrame) button closing over a JFrame? and after back i wants to be frame get disposed system get exited.

I have setted default closing Operation setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

Upvotes: 0

Views: 43

Answers (1)

akourt
akourt

Reputation: 5563

Very simply by doing the following:

  1. Setting the default close operation to:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

  1. Adding a new WindowAdapter to your frame and override (hooking) on its windowClosing method like so:
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent event) {
        //your logic here
    }
});

Also don't forget that you will need to manually dispose the frame as well as call System#exit once done in order to close the application.

For more check the related documentation here:

https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/WindowAdapter.html

Upvotes: 2

Related Questions