Closing a java program properly when JDialog is the main window

jax picture jax · Aug 25, 2011 · Viewed 12.6k times · Source

I have a JDialog as the main window in my application (originally it was a JFrame but it showed in the taskbar which I didn't want).

Currently I am doing:

setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

and when I click an exit button:

frame.dispose();

But the process still seems to hang around in the background

JFrame had JFrame.EXIT_ON_CLOSE which seemed to do what I wanted.

How can I close my application properly?

Answer

Itay Maman picture Itay Maman · Aug 25, 2011

You need to add a WindowListener that will do System.exit(0) when the dialog closes.

JDialog dialog = ...;
dialog.addWindowListener(new WindowAdapter() { 
    @Override public void windowClosed(WindowEvent e) { 
      System.exit(0);
    }
  });

Of course, the System.exit(0) after you hit the Exit button (that was suggested elsewhere in this thread) is still needed.