java swing program not closing after dispose is ca

2020-04-21 04:51发布

问题:

Preface: This is the first real swing program I have done.

I have a swing program, where one JButton is supposed to exit the program. That button triggers this.dispose();. When i click this JButton, it does make the window completely go away, but looking at the debugger, the program itself is still running.

My main method only consists of:

public static void main (String[] args)
{
  java.awt.EventQueue.invokeLater(new Runnable()
  {
    public void run()
    {
      new StartupGui().setVisible(true);
    }
  });
}

My exit button looks like action button looks like:

private void exitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
  this.dispose();
}

I have also tried this for the exit button:

private void exitButtonActionPerformed(java.awt.event.ActionEvent evt)
{
  java.awt.EventQueue.invokeLater(new Runnable()
  {
    public void run()
    {
      dispose();
    }
  });
}

Looking at the debugger after i press the exit button, i see the following (and only the following):

Daemon Thread [AWT-XAWT] (running)
Thread [AWT-Shutdown] (running)
Thread [AWT-EventQueue-0] (running)
Thread [DestroyJavaVM] (running)

Can anyone point me in the right direction as to why the program isn't shutting down after this point? I have done some googling but haven't gotten anywhere thus far. If you need any more information, just let me know

Thanks :)

回答1:

Because dispose() method only releases the resources.

The doc has a

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.

Did you notice the may?

The link above gives you detailed information about the Auto shutdown feature. You can read more about that, or you can simply solve this by replacing this.dispose() with System.exit(0)



回答2:

This Pushing Pixels article: AWT shutdown and daemon threads discusses the AWT shutdown behaviour that was changed in 1.4. Still, the article notes that it can be tricky to get a clean shutdown.

Without seeing the rest of the code, I can only offer pointers:

  • ensure there are no other hidden frames that have not been disposed
  • ensure no messages are being generated on the AWT queue (i.e. set a breakpoint in the EventQueue.)
  • otherwise look at the stack frame for these threads and see what they are busy doing