-1

I have a JFrame and I would like to know when the close button is clicked for that JFrame. When the JFrame is closed my whole project does not close so I want to be able to tell when the user closes that one Frame.

I've tried using methods like as !f.isShowing and !m.f.isActive() but when I close the Frame, what I want to happen doesn't.

Roman C
  • 49,761
  • 33
  • 66
  • 176
user3341532
  • 1
  • 1
  • 1
  • Read this: http://stackoverflow.com/questions/1234912/how-to-programmatically-close-a-jframe?rq=1 – user123454321 Feb 22 '14 at 19:19
  • I don't want to close it, I want to know when the user closes it. – user3341532 Feb 22 '14 at 19:19
  • Just to be clear, do you simply have a problem with the run not ending when the frame closes, or do you want to do something when the frame closes? Because both are mentioned in your question. – BitNinja Feb 22 '14 at 19:27
  • 1
    I have to wonder if this isn't really an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) in disguise and if what you really want is to use a modal JDialog. If you tell us more of the background story, we may be able to give you a much better answer. – Hovercraft Full Of Eels Feb 22 '14 at 19:35

3 Answers3

4

If you don't want to do anything special when the frame closes, you can use setDefaultCloseOperation to change the way a JFrame

EXIT_ON_CLOSE

The exit application default window close operation. If a window has this set as the close operation and is closed in an applet, a SecurityException may be thrown. It is recommended you only use this in an application.

HIDE_ON_CLOSE

The hide-window default window close operation

DISPOSE_ON_CLOSE

The dispose-window default window close operation. Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1
import javax.swing.JOptionPane;
frame.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        if (JOptionPane.showConfirmDialog(frame,...) ...) {
            // ...
            System.exit(0);
        }
    }
});
dic19
  • 17,821
  • 6
  • 40
  • 69
user123454321
  • 1,028
  • 8
  • 26
0

when the JFrame is closed my whole project does not close...

A common cause of this is that when you declare a JFrame you should call this method of JFrame to make it close when you press the 'x' button:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BitNinja
  • 1,477
  • 1
  • 19
  • 25