Tomáš Zato
Tomáš Zato

Reputation: 53149

How to avoid JFrame.EXIT_ON_CLOSE and gracefully terminate the swing program

I don't like the JFrame.EXIT_ON_CLOSE option very much. If there's a thread writing a file, or downloading something the option will be killed before it can complete. Instead, I was trying to terminate the program gracefully by destroying the GUI window:

   /**
    * Terminates the whole program while saving settings.
    */
   public void Terminate() {
     //gui is JFrame representing the application window
     gui.setVisible(false);
     gui.dispose();
     gui.destroyTray();
     //Stop tool thread if running
     if(ToolRunning())
       StopTool();
     //Save settings
     if(settings==null) {
       System.out.println("Settings is null!");
       return;
     }
     try {
       settings.loadSettingsFromBoundFields();
       settings.saveToFile(SETTINGS_FILE, false);
     }
     catch(IOException e) {
       System.err.println("Problem saving settings:");
       e.printStackTrace(System.err);
     }
     //Here, no non-deamon threads should be running (daemon thread does not prolong the applicatione execution).
   }

But the program keeps running and the Swing threads do not exit when I dispose() the JFrame. What else could be blocking Swing? When I made a simpler program using the same approach (hide window and dispose()) it worked. This means complexity of my project is hiding something that leaked. How can I find what is blocking Swing threads from terminating?

Upvotes: 1

Views: 1142

Answers (1)

scir
scir

Reputation: 74

Have you tried this https://docs.oracle.com/javase/8/docs/api/java/awt/doc-files/AWTThreadIssues.html , i.e. Frame.getFrames

Upvotes: 1

Related Questions