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.

10 Years
Discussion Span
Last Post by leiger

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?



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

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

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

Votes + 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.


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

Edited by leiger: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.