views:

103

answers:

2

I want to write a component that monitors other activities, but it's listeners are to be removed when the component's window is closed.

I don't want to write this removal code many times, but want the component to handle it itself. (How) can i do it?

Thanks!

+2  A: 

The JFrame class (which is the window) has a processWindowEvent callback that takes a single parameter called Windowevent

Register this callback and if the parameter is of WINDOW_CLOSED you can call the removal code inside.

In the end the removal code is only written once (as you want it).

See the API for more details.

Update: See also this

kazanaki
How can i put this listener, when i'm writing a component? I dont't have reference to the JFrame, only to the parent component.
Szundi
You pass the JFrame reference of your application in the construction of your custom component and store it in a private variable inside the class of your component.
kazanaki
okay, maybe that's the way it should be done. i just hoped we have a way obtaining the jframe or something
Szundi
as your comment precedes Pierre's code, you got the point
Szundi
+1  A: 

I would write something like that

class ListenToWindow
extends WindowAdapter
{
MyInternalFrame frame;

public void windowClosed(event)
   {
   this.frame.removeAllTheRequiredListeners();
   }
}

(...)
JFrame window;
MyInternalFrame frame;
(...)
window.addWindowLister(new ListenToWindow(frame));
(...)
Pierre