I want to create a ‘generic’ JPanel which can be rendered in any of the 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.
There’s a few different options depending on the exact semantics you want. You can register a
ComponentListenerand handle thecomponentHiddenmethod. Another possibility is to register aHierarchyListenerand check forDISPLAYABILITY_CHANGEDevents. You could also use aHierarchyListenerto 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 theComponentListenerandHierarchyListeneris that theComponentListeneris triggered by any visibility change while theHierarchyListener/DISPLAYABILITY_CHANGEDevent is triggered when the panel’s window is disposed.ComponentListeneris probably your best bet, but be aware that the panel might be set as visible again in the future.You can also try the
AncestorListenerancestorRemovedevent. It’s called if the component itself or any of it’s ancestors is made invisibile.