I am trying to listen for a window close event on a parent JFrame from a JPanel. In the WindowClosing event, I would like to de-register the listener to another component.
Unfortunately, the only code I can run to run is the panel constructor. This means that the panel itself does not yet have an ancestor window, so just calling SwingUtilities.getWindowAncestor does not work. Therefore, I register a hierarchy listener, and in the hierarchyChanged event, the SHOWING_CHANGED event. When it even works, now I can search for the ancestor of the panel window.
So basically I have the following:
class ShapeControlPanel extends JPanel{ public ShapeControlPanel(){ final ShapeControlPanel me = this; me.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == HierarchyEvent.SHOWING_CHANGED){ SwingUtilities.getWindowAncestor(me).addWindowListener(new WindowListener() { @Override public void windowClosing(WindowEvent e) { me.getApparent().removeLocationSelectionListener(me.GUID(), me); } }); } } }); } }
It's great? Is there a smarter way to get a handle to a frame closing event?
source share