1

How can I get a JTree to only listen to its TreeModel while it is actually visible to the user or at least to have it unregister itself as soon as the corresponding JFrame is disposed?

As far as I can see the only case a JTree unregisters itself from its model is if you pass it a new model (using setModel(…)).

This causes the tree not being garbage collected if the model is referenced from somewhere else. Example: I implemented a TreeModel using a WatchService to have an always up to date model of a file system tree. Even a single listener on the model requires me to keep the WatchService informing the model about file system changes, so it cannot be garbage collected. So even if the JTree is not visible anymore it is still kept in memory by the model which still needs to get updates from the WatchService, although none of this is necessary any longer.

I guess the best way would be to create a new class extending JTree that does the registering to and unregistering from the model. If so, which methods are called when the component is shown or disposed? Probably addNotify() and removeNotify() are good candidates?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
siegi
  • 5,646
  • 2
  • 30
  • 42

1 Answers1

0

Using the documentation of JTree: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTree.html.

JTree has a protected field called treeModelListener which you can remove from the model directly using JTreeModelListener.removeTreeModelListener(). If you want to remove your tree model from its own listener at will, extend JTree and add the following method:

public void unregisterOrWhatever() {
    this.treeModel.removeTreeModelListener(this.treeModelListener);
}

If you want to get fancy with listening for window closing events, add a HierarchyListener to your JTree which listens for HierarchyEvent.PARENT_CHANGED events. Whenever the JTree is added to a new window, you can add a WindowListener unregisterOrWhatever when the window is closed. Don't forget to also remove the WindowListener when the JTree is removed from a window.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264