How can I wait until the component appears in Java?

I have a component ( JPanel ) inside a Window . I always get false when I call panel.isShowing() , when called from the windowGainedFocus() event (when the parent window receives focus).

I assume that when the windowGainedFocus() event is windowGainedFocus() , the JPanel picture inside this Window is not yet complete.

I tried to place this call to isShowing() using the paint() method of this Window , but I always get isShowing() = false .

Is there a way to get an event when the JPanel fully displayed on the screen and the isShowing() method returns true?

thanks

+4
source share
3 answers

Probably your best bet is to use the hierarchy listener in the panel itself:

 panel.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { if ((HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags()) !=0 && panel.isShowing()) { //do stuff } } }); 
+12
source

If you do not want an event, but have specific code that must be run after your component has been drawn, you can override addNotify() , which is called to make the component visible. Example:

 public void addNotify() { super.addNotify(); // at this point component has been displayed // do stuff } 
+1
source

The component will be fully displayed after receiving WindowListener.windowActivated. You will also encounter time issues and race conditions when trying to assign focus to the windowActivated event.

0
source

All Articles