开发者

How do I Hook a JPanel into parent/ancestor Container's windowClosing/Closed listener?

I want to create a 'generic' JPanel which can be rendered in any of the开发者_Go百科 higher level Window classes (JFrame, JDialog, or JInternalFrame to be somewhat precise.)

I want to be able to 'clean up' some static values when that window is no longer being rendered on screen. Normally, I would do this with a Window class (like JFrame) and simply addWindowListener with proper windowClosing or windowClosed methods during the creation of the JFrame.

Since I desire any of the Window classes to be able to render this, I don't even know which kind of listener to add nor do I know which window to add it to.

Is there a way to 'hook' the realization and rendering of the JPanel to so that I can add my shutdown hooks no matter what Window class renders it?

(I looked at PropertyChangeListener, but componentShown doesn't trigger on the JPanel rendering.)

Any help would be appreciated.


Well, I finally got something working, but I'm not sure I really like the answer.

I added an AncestorListener to the JPanel at creation. This listener stubbed out the ancestorRemoved and ancestorMoved events and in the ancestorAdded event, would hook the getTopLevelAncestor() with the appropriate WindowListener/InternalFrameListener so that I could run my shutdown code when the window closes.

If there's a better way, I'm open to it. (I'm going to be reviewing the HierarchyListener from Geoff.)


There's a few different options depending on the exact semantics you want. You can register a ComponentListener and handle the componentHidden method. Another possibility is to register a HierarchyListener and check for DISPLAYABILITY_CHANGED events. You could also use a HierarchyListener to find when the panel has been added or removed from a container and add/remove window listeners from the old and new window. The difference between the ComponentListener and HierarchyListener is that the ComponentListener is triggered by any visibility change while the HierarchyListener/DISPLAYABILITY_CHANGED event is triggered when the panel's window is disposed. ComponentListener is probably your best bet, but be aware that the panel might be set as visible again in the future.

You can also try the AncestorListener ancestorRemoved event. It's called if the component itself or any of it's ancestors is made invisibile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜