Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java swing: add custom graphical button to JTree item

Tags:

java

swing

jtree

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!

like image 495
clamp Avatar asked Aug 18 '10 08:08

clamp


2 Answers

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()));
like image 92
GiantLeprechaun Avatar answered Oct 05 '22 20:10

GiantLeprechaun


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

like image 44
YoK Avatar answered Oct 05 '22 19:10

YoK