Nathan Campos
Nathan Campos

Reputation: 29497

OnExit Event For a Swing Application?

I'm developing a simple application to manage the operational part of a business using Swing, but I need that when the application exits, it performs this:

updateZonas();
db.close();

But how can I do this?

Upvotes: 16

Views: 24164

Answers (3)

Santhosh Kumar Tekuri
Santhosh Kumar Tekuri

Reputation: 3020

Runtime.getRuntime().addShutdownHook(new Thread()
{
    @Override
    public void run()
    {
        updateZonas();
        db.close();
    }
});

This works for any Java application(Swing/AWT/Console)

Upvotes: 35

Enrique
Enrique

Reputation: 10127

Are you using a JFrame? if so you can try this:

    myframe.addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(WindowEvent winEvt) {
            updateZonas();
            db.close();
            System.exit(0);
        }
    });

Upvotes: 29

lins314159
lins314159

Reputation: 2520

Add a WindowListener to your JFrame. Its windowClosing method would call whatever code you need, then System.exit(0) (or some other return code).

Upvotes: 7

Related Questions