I am trying to implement a listener to detect the closing of a window. My main class is extending other classes so I am unable to extend JFrame which is not allowing me to use addWindowListener.
I have tried the code below but it is not working.
public class PowerPanel extends AnotherPanel implements ActionListener, PropertyChangeListener {
// logic …
this.addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent e ) {
// do things
}
});
}
The error I am getting is indicating that addWindowListener is "undefined for the type PowerPanel."
You can't add window listener to your panel - you need to add it into the
java.awt.Windowinstance which in your case is aJFrame.If it is hard for you to pass your
JFrameinstance into the panel - you can access it in a different way:With this code your panel will automatically register window listener on it's parent window whenever it is displayed. It will also automatically remove the listener once panel is hidden or removed from the window, so potentially this is the best solution you can have.
Be careful though, if you will use that panel multiple times on the same window - all of the instances will add their own listener and will all perform on-close action separately. If you want to perform your on-close operation just once per window/frame/dialog instance - you need to add the listener on the window itself, preferably where it is created not to make it obscure.
You might also notice that in my example there is actually a method that retrieves panel's parent window directly:
Although you can't use it in your panel directly, because at the moment when panel is created it is not yet added into any container, let alone visible window. That is why the solution with ancestor listener that i've shown is required.