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.