Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to customize the JTree's Icon and keep original icons unchanged??

sunnycodeMay 10 2007 — edited Aug 13 2008
Hi,

I used the following code from an example:

see link
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

//...where the tree is initialized:
    //Enable tool tips.
    ToolTipManager.sharedInstance().registerComponent(tree);
    
    ImageIcon tutorialIcon = createImageIcon("images/middle.gif");
    if (tutorialIcon != null) {
        tree.setCellRenderer(new MyRenderer(tutorialIcon));
    }
...
class MyRenderer extends DefaultTreeCellRenderer {
    Icon tutorialIcon;

    public MyRenderer(Icon icon) {
        tutorialIcon = icon;
    }

    public Component getTreeCellRendererComponent(
                        JTree tree,
                        Object value,
                        boolean sel,
                        boolean expanded,
                        boolean leaf,
                        int row,
                        boolean hasFocus) {

        super.getTreeCellRendererComponent(
                        tree, value, sel,
                        expanded, leaf, row,
                        hasFocus);
        if (leaf && isTutorialBook(value)) {
            setIcon(tutorialIcon);
            setToolTipText("This book is in the Tutorial series.");
        } else {
            setToolTipText(null); //no tool tip
        } 

        return this;
    }

    protected boolean isTutorialBook(Object value) {
        DefaultMutableTreeNode node =
                (DefaultMutableTreeNode)value;
        BookInfo nodeInfo =
                (BookInfo)(node.getUserObject());
        String title = nodeInfo.bookName;
        if (title.indexOf("Tutorial") >= 0) {
            return true;
        }

        return false;
    }
}
I use above code to customize the Icon of JTree at run time.
When I Drag and drop the node/leaf into this Jtree, I can successfully see the JTee's icon was changed with new coming Icon, but problem is that the whole tree's Leave's icon were replaced by new COMING new leaf/node's icon, what I want is that I hope to keep all previous leaves/nodes' icons untouched or unchanged, not replaced by new coming icon, how to implement this??

Can any guru give some valuable advice??

Really thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 10 2008
Added on May 10 2007
11 comments
232 views