Trying to terminate a swing gui, start the same gui and terminate it.
I am using the answer to this question but it seem to only work once.
The code below cycles once and hangs after printing 2.
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
public class Hello {
void createAndShowGUI() {
frame=new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label=new JLabel("Hello World");
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
void goodbye() {
WindowEvent wev=new WindowEvent(frame,WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
}
static void helloGoodbye() throws InterruptedException,InvocationTargetException {
System.out.println("enter");
final Hello hello=new Hello();
System.out.println("1");
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
System.out.println("3");
hello.createAndShowGUI();
System.out.println("4");
}
{
System.out.println("2");
}
});
System.out.println("5");
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
hello.goodbye();
System.out.println("6");
}
});
// Thread.sleep(1000);
System.out.println("exit");
}
public static void main(String[] args) throws InvocationTargetException,InterruptedException {
for(int i=0;i<10;i++)
helloGoodbye();
System.out.println("exiting main");
}
JFrame frame;
}
Why doesn't it work?
The program doesn't hang but rather it exits because:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
From the doc:
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
Here, it seems like DISPOSE_ON_CLOSE
will result in the behavior you are expecting. I also do not really see a reason to be posting this window closing event when you can call setVisible(false)
and dispose
. Without making assumptions about what the program is actually intended to do, both of these options will result in all 10 frames being shown/hidden/disposed.
I would guess that the reason the program halts after printing the '2' is that calling invokeAndWait
causes any previously queued events to be pumped, including the window closing event.