Join Window Events from JPanel

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() { /* Snipped some empty handlers */ @Override public void windowClosing(WindowEvent e) { /* Finally get to remove the handler. */ me.getApparent().removeLocationSelectionListener(me.GUID(), me); } }); } } }); } } 

It's great? Is there a smarter way to get a handle to a frame closing event?

+4
source share
1 answer

This is not the ugliest thing I have seen (I would not even say it all so badly), but you should ask yourself: why does your panel really need to know when the window is closed? This seems to be a weird connection that is best removed.

I do not know enough about your context and what you are really trying to do to offer an alternative right now. But if the panel needs to know about the container in which it is located, there is probably a poor design with a bad connection.

+3
source

Source: https://habr.com/ru/post/1339414/


All Articles