views:

719

answers:

2

I need to add checkboxes to a JTree. A custom TreeCellRenderer/TreeCellEditor seems like the right approach. So far I used the CheckBoxNodeRenderer approach in this webpage. It works OK except for two things:

  1. there's additional whitespace above + below the checkbox; I'd like to keep it the same as a regular JTree.
  2. I would like to distinguish between clicking on the checkbox itself (which should attempt to toggle the checkbox) and clicking on the text associated with the checkbox (which should allow an event listener to interpret this as clicking on the corresponding tree node and take whatever action is appropriate)

is there a way to do these things? I looked around for JTrees with checkboxes, can't find much. JIDE looks good but I need to use free open-source software (GPL is not ok, LGPL is ok) in this case. (or create my own checkbox tree)

+3  A: 

As for #2, you could make a panel be the editor/renderer, and add a label along with the checkbox - the label would be the text, and the check box would not have the text added to it.

aperkins
oh, that's a good idea, I hadn't thought of that.
Jason S
Just be aware that if you just copy the DefaultTreeCellRenderer code and replace the extension of JLabel with a JPanel, you'll also have to remove a lot of the "overridden for performance" methods or you'll have a blank JTree.
Jay R.
+2  A: 

per @aperkins suggestion this is what I ended up doing in the TableCellRenderer, it seems to work well:

final private JPanel nodeRenderer = new JPanel();
final private JLabel label = new JLabel();
final private JCheckBox check = new JCheckBox();

     ...

// in constructor:
final Insets inset0=new Insets(0,0,0,0);  
this.check.setMargin(inset0);
this.nodeRenderer.setLayout(new BorderLayout()); 
this.nodeRenderer.add(this.check, BorderLayout.WEST);
this.nodeRenderer.add(this.label, BorderLayout.CENTER);

The keys for getting rid of unwanted space in the margins seems to be (a) calling JCheckBox.setMargin() to reduce the checkbox margin, and (b) using a BorderLayout for JPanel.

Jason S