How to listen for close in a JPanel

jspacek picture jspacek · Jan 18, 2013 · Viewed 10.6k times · Source

I am working with some strange legacy code. They have a custom object which implements a JPanel. This JPanel object is a secondary popup screen within the main application. The issue I'm having is to detect when the secondary popup screen is closed.

I tried to implement a WindowListener for the class, but when I try to add it, there is no JFrame associated with this object. I am assuming this is because they are using a custom object and it is an embedded popup screen.

I tried to retrieve a JFrame using:

JFrame parentFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

which fails on a NullPointerException. I have no idea why it's so difficult to detect the right hand corner "x" close button on this page! I should mention that they were able to add Mouse and Key Listeners to the table which is embedded within the JPanel. But the outside listener for the entire window is causing me troubles.

(Please bear with me, this is my first stackoverflow post and I am new to Swing.)

Thanks so very much!!

Answer

Audrius Meskauskas picture Audrius Meskauskas · Jan 18, 2013

Try to call getParent() for that strange panel. It should return the parent GUI component. If this is still not your frame but some intermediate panel instead, call getParent() on it as well. The top level component returns null.

   Component p = strangePanel;
   while ( p != null && ! (p instanceof Window))
     p = p.getParent();

   ((Window) p ).addWindowListener(..);