tags:

views:

18

answers:

2

Hi Guys,

I have a main program which calls a JFrame to get User information, If a user press submit I am storing the information in POJO and getting it into Main program.

If User clicks on Exit, I want to dispose the JFrame and want to exit the main program as well after executing one logging statement in main method.

If I use -

 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
and
this.addWindowListener(new WindowAdapter() {
            public void windowClosed(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

all the Threads exit immediately and I am not able to execute logging statments in main method.

If I use-

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 this.addWindowListener(new WindowAdapter() {
            public void windowClosed(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

My main method execute those logging statments but it never exit, It stay silent after executing all the statements.

If I use this -

this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 this.addWindowListener(new WindowAdapter() {
            public void windowClosed(WindowEvent e) {
                Thread.currentThread.interrupt();
            }
        });

Everything works fine. But is it the correct way of doing this?

enter code here
A: 

Dispose method only releases system resources. To actually close the window you have to call setVisible(false)

eugener
A: 

In theory, if you dispose all top-level windows, the JVM should terminate cleanly.

However, there are a few details to make sure, which are detailed on this page:

Therefore, a stand-alone AWT application that wishes to exit cleanly without calling System.exit must:

  • Make sure that all AWT or Swing components are made undisplayable when the application finishes. This can be done by calling Window.dispose on all top-level Windows. See Frame.getFrames.
  • Make sure that no method of AWT event listeners registered by the application with any AWT or Swing component can run into an infinite loop or hang indefinitely. For example, an AWT listener method triggered by some AWT event can post a new AWT event of the same type to the EventQueue. The argument is that methods of AWT event listeners are typically executed on helper threads.

If you don't manage to find what keeps the program alive, there can be another way:

-Use the first method you described, with the EXIT_ON_CLOSE
-Add a ShutdownHook to the runtime, to execute your last logging statements:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        //logging statements
    });
Gnoupi