Sorry if this has been asked before.

I have a jframe with a textcomponent in it and a menu with an exit option. When you select the exit option a funciton is called that checks whether a change has been made to the document and the user can select to quit anyway or save changes etc.

What i need is to call the same function when the close button in the top right of the jframe is selected.

Any help would be appreciated, thanks.

Just a brief look through the API (starting from JFrame's setDefaultCloseOperation()) took me to WindowListener, which might be what you're looking for.

Ok thanks it's working.

But i've got another problem.

When the user tries to close the application it asks if they want to save their changes (if they have made any). They can select ok (to save) no (to exit) and cancel.

The problem is that i want cancel to allow them to continue using the application, however it continues to exit.

Is there anyway that i can override the exit operation?

Thanks.

Would you mind posting the solution, just for if someone reads the thread later? (And I'm remotely curious as to how to do it as well ;))

JFrame f = new JFrame();

//disable the close button
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

//create custom close operation
f.addWindowListener(new WindowAdapter()
{
      public void windowClosing(WindowEvent e)
      {
          exitProcedure();
      }
});

in the exitProcedure method i just use an if else ladder to work out if i need to save or exit etc.

Comments
Thanks! I needed this solution and this was the only place I found it!

THANK YOU Cerberus! :) I was having the same problem and tearing my hair out trying to figure out how to make it stop exiting when the user said "no" (to stop/cancel)

I had a slight variation on your code as I was already using a method for my File>CloseFile and File>ExitApplication menu items. It returns a boolean to say whether the user wants to continue (the message that appears is generic.. "Continue without saving?" and applies to both closing the file and exiting the application).

My guess is that your exitProcedure() method has System.exit() hard coded in, which would prevent you from being able to close only the current document but keep the application itself running.

Cheers,
Shane

Edit: Sorry, just realised this thread was last updated Feb 10th, 2007. Sorry for the bump :|

Edited 6 Years Ago by leiger: n/a

This article has been dead for over six months. Start a new discussion instead.