Monthly Archives: January 2005

Java Swing Component Lifecycle methods 101

In case you were wondering…..

Swing components have a number of methods that are called when things happen. Two useful ones are the addNotify and removeNotify methods. These are called when a component is added to a container, or removed from a container (as the names suggest).

Of particular interest when working with Swing components is knowing when they are removed from the screen. Happily this components are notified of this by having their removeNotify method called. The Java Container class will call this at all appropriate times, even if components are thrown away carelessly without a thought for pollution, or the environment.

The good thing about having the removeNotify method called is that a component can be morally responsible, and clean up after itself. In fact it could even do the evironment a favour by recycling.

A practical use of this approach is to clean up any stray threads that might be created by a component. Especially if the thread isn’t required when the component isn’t visible.

If the thread is needed again, it could be recreated again through the use of the addNotify method.