views:

41

answers:

1

I have been looking into JTree and TreeCellRenderer. It seems in general, the application (with one JTree) has only one instance of TreeCellRenderer. The application makes multiple calls to TreeCellRenderer's getTreeCellRendererComponent method to decide how each TreeCell is drawn, and such call are made in many occasions (when a cell is selected, deselected, move over, when scrolling, etc.). Why did they decide to do that instead of having multiple instances of TreeCellRenderer, each responsible for one cell??

I am trying to make a JTree where each cell contains a checkbox. The checkbox can be checked/unchecked by the user. Then, the TreeNode userObject's values are set base on the state of these checkboxes. But, from the current JTree design this is impossible - since there is only one instance of JCheckBox, and is only used to show how the Cell looks like (you can't really check it). In some sense I want to separate selection of the TreeCell and the checking of the boxes.

I have some workarounds (implementing MouseAdapter and checking if the mouse click is close by where the checkbox is rendered, then emulate a check on the box by changing its appearence in TreeCellRenderer), but still I want to know if this can be done more directly. Thanks!

+2  A: 

Why did they decide to do that instead of having multiple instances of TreeCellRenderer, each responsible for one cell?

This is a nice example of the flyweight pattern.

For a check box tree, I like org.netbeans.swing.outline.Outline, mentioned here, but other examples are available.

Addendum: Reading your question more closely, you ask:

In some sense I want to separate selection of the TreeCell and the checking of the boxes.

This is the correct instinct: The data (checked or unchecked) should be stored in the model (TreeModel), not the view (JCheckBox). The example uses instances of CheckBoxNode in it's (implicit) model, accordingly.

trashgod
I studied that example before. It is not exactly what I want: they check the box whenever a node is selected, but I only want to check the box when the mouse clicks the checkbox, and not whenever the mouse clicks the cell. By the way, the example have a bug. In the mouseClicked method, you actually need to call tree.revalidate(); even when row is not 0. Otherwise some children cells won't be updated in DIG_IN mode.I'll look into the Outline object. Thanks.
Raymond
@Raymond: You are welcome.
trashgod
Hmm.. It seems the netbeans package are not part of standard java, is that true? If my program uses those, then anyone using the code would need to install netbeans too right?
Raymond
@Rayomnd: `org-netbeans-swing-outline.jar` is included in NetBeans, but it has no dependencies external to standard Java. See http://netbeans.dzone.com/news/taking-new-swing-tree-table-a-
trashgod