tags:

views:

1108

answers:

3

I'm implementing a Java JTree panel. This panel holds a TreeModel build from a set ofdatastructures that are treelike (a list of lists of composites - different classes). I get these datastructure from external jar implementations based on a set of interfaces I defined.

The treenodes contain a checkbox that the user may check to indicate that the checked node and all child nodes are to become "active", that is, the objects that are represented by the nodes should do something, like getting data from a database.

The treenodes may also be selected without "activating" them, that is, without the checkbox being checked.

On top of that, other parts of the program may also toggle the activation state of the datamodel objects. So the data model out of which the treemodel is build is the source of the activation state. This must be reflected in the treeview by dynamically (un)checking the checkbox.

Now, how do I implement this whole? Who should be listeners for what changes?

I now have all the classes that are in the nodes extend from an abstract class that holds an activation field. This is the true datasource. When this field changes, all subscribed listeners (EventListener) should be notified, This includes the checkboxes.

I also have a TreeSelectionModel that is based on the default TreeSelectionModel but extended with functionality to check if children/parents need to be checked.

My questions maybe is not really clear, but so is this complex piece of code. Hope you can help.

A: 

You seem to have a bunch of moving parts. It might be good to funnel all changes through your TreeModel, and have your JTree be the listener, as it will be automatically. If your TreeModel is a subclass of [DefaultTreeModel][1], you get a host of fire* (fireTableStructureChanged, fireTreeNodesChanged, etc.) methods which will alert your JTree to repaint. Make sure you do this firing of events in the AWT EventQueue.

here is a good tutorial with a load of examples for using Trees.

akf
+1  A: 
A: 

It sounds to me like you have the right idea -- make the node the canonical source for the "activated" knowledge, and the canonical source of activation events. Then you can have the TreeModel listen to that and translate those events into fireTreeNodesChanged() etc, which should cause the JTree to update itself automatically.

To keep yourself out of trouble, try to keep the node -> tree event relationship one way -- that is, don't use the tree as a controller, don't allow tree events to change the activation state.

David Moles