问题
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!
回答1:
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
回答2:
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()));
回答3:
You can add a TreeCellRenderer to your JTree. This Renderer can render an Icon on each element of the tree.
回答4:
From the JTree Javadoc:
To use JTree to display compound nodes (for example, nodes containing both a graphic icon and text), subclass
javax.swing.tree.TreeCellRenderer
and usesetCellRenderer
to tell the tree to use it.
A compound node is what you want. You have to implement on single method which will return a Composite
object which is in, in your case, a small panel containing a button and a label side by side.
来源:https://stackoverflow.com/questions/3510253/java-swing-add-custom-graphical-button-to-jtree-item