i would like to add an additional button with a small icon to the right of an item in a JTree. can this be done? if so, how?
thanks!
Clamp,
Did you have success with this? I wanted to do the same thing and had a hard time getting the JButton to respond to the user. Setting up the renderer to get the button to display went smoothly, but all mouse events were handled by the JTree itself and not passed along to my button.
I finally found a solution and thought I would post it here for others to comment on (maybe there is a better way?)
In addition to my custom renderer, I also created a custom editor that extends DefaultTreeCellEditor. My custom renderer is passed into the custom editor via the constructor. In the editor I override isCellEditable to return true and I override getTreeCellEditorComponent to return renderer.getTreeCellRendererComponent. This was the key. It returns the renderer component so then all clicks are passed to my panel within my custom renderer and my JButton then responded normally to action events.
Here is my editor:
public class MyTreeCellEditor extends DefaultTreeCellEditor {
public MyTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
super(tree, renderer);
}
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row) {
return renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf, row, true);
}
public boolean isCellEditable(EventObject anEvent) {
return true; // Or make this conditional depending on the node
}
}
On your tree, be sure to set your custom editor:
myTree.setCellEditor(new MyTreeCellEditor(myTree, (DefaultTreeCellRenderer) myTree.getCellRenderer()));
You will need to CustomCellRenderer which implement TreeCellRenderer, and attach it to JTree.
In your CustomCellRenderer you can put button and icon.
JTree tree = new JTree(rootVector);
TreeCellRenderer renderer = new CustomCellRenderer();
tree.setCellRenderer(renderer);
Check this example: (referenced above code from here)
http://www.java2s.com/Code/Java/Swing-JFC/TreeCellRenderer.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With