How To: Main Thread waits for Event Dispatching Thread?
Please help in following question:
how to sleep Main Thread until the frame closure.
This is sample code
publicstaticvoid main( String[] args ){
JFrame frame =new JFrame();
...
frame.setVisible(true );// JVM starts Event Dispatching Thread
// ? sleeping Main Thread
// below operators execute after the frame was closed
...
}
P.S. this is the main frame and I can not use JDialog instead.
[781 byte] By [
m.shostaka] at [2007-11-27 4:06:07]

# 1
Instead of using a busy loop, I would recommend a WindowListener.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("frame closed");
}
});
# 3
> Thanks, but this doesn't fit my needs.
> I'm implementing my own an application controller
> class and the frame don't know about the application
> view management.
But the application view management will know about the frame right? Otherwise who creates it? Wherever the frame is created, that code can listen to the frame's window events without the frame ever knowing about it.
At any rate, is this what you're looking for?
frame.setVisible(true);
while (frame.isVisible()) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
System.out.println("frame closed");
# 4
Actually I just gave you bad advice because frames should technically be shown in the EDT:
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setVisible(true);
}
});
In which case the busy loop won't work because the frame won't be visible yet after scheduling that task and it will immediately bail out of the loop. I still think using a WindowListener is the best choice, if you can find a way to make that work.
# 5
windowClosing() listener already exists inside my frame class. Is closes the frame in my way. But the frame does is not the application.
The application must control the life-cycle.
Currently I implemented the following approach:
(in the main() method)
...
// Display main frame
frame.setVisible(true);
// Sleep Main Thread
try{
while( frame.isDisplayable() ){
Thread.sleep( 1000 );
}
}
catch( final InterruptedException exception ){
exception.printStackTrace();
}
// Continue executing MainThread
...
It works, but I feel it is not absolutely correct. However it is good because the frame steel does not know about my (Application Controller) thread problems.
I think about passing to the frame class the reference of the MainThread and call its notify() method when frame closes and wait() for that notification in the loop in main().
Another thought is to join() the EDT to wait for its stop. But I don't know how to obtain it in Main Thread.
P.S. It seems to me that in recent JDKs (5 and 6) frame is showed in the EDT anyway (whether you use invokeLater() or not).