views:

97

answers:

3

I have a program that creates a JFrame and makes it visible. Is there anyway to know when the JFrame is fully drawn and visible? Right now a hacky "wait and pray" method is being used.

Thanks for the help!

+2  A: 

You could add a WindowListener to the JFrame; then when windowOpened is fired, the window should be visible.

Michael Myers
Oh, wait, you were probably wanting a listener or some such thing. Deleting...
Michael Myers
Its something, I hate polling since I'm just moving my wait somewhere else...
Sandro
Changed to a listener approach (for reference, the original answer suggested checking isShowing()).
Michael Myers
Ok I just realised that I am asking the wrong question. I'm creating a JFrame in a thread, then I want that thread to wait for the Jframe to appear. But since that frame doesn't exist yet I have no way to grab a reference to it. (Of course I'm using reflection to create the frame, just to complicate things). So I think that the real question is "How can yield and specifically wait for the Swing thread to execute". Should I make a new question?
Sandro
A: 

You can also try overriding Component.addNotify() which I believe is called when the component is drawn. Just make sure to call super.addNotify().

public void addNotify() {
    super.addNotify();
    // after displayed handling
}
Steve Kuo
+1  A: 

to answer the "How can yield and specifically wait for the Swing thread to execute" question:

you can use a SwingWorker.

edit reading your comment once more i see a potentially problematic statement:

I'm creating a JFrame in a thread, then I want that thread to wait for the JFrame to appear.

are you calling your frame.setVisible(true) in this thread as well? If so, you should probably be reminded that Swing painting should all be handled on the AWT EventQueue. This is where the SwingWorker comes in.

However, what you may need for the 'yield and wait' is a wait/notify operation. In your calling thread you can wait on a shared Object:

synchronized (frameShowingLock) {
     frameShowingLock.wait()'
}

then in your SwingWorker, or wherever you call frame.setVisible(true) you can finish the process by using the notifyAll() method to wake up your waiting thread:

 synchronized (frameShowingLock) {
     frameShowingLock.notifyAll()'
}
akf
how specifically? I'm not exactly sure how it helps. Thank you.
Sandro
bingo! thank you!
Sandro