Lever icon in jtree

i want to remove blue lever shown with each branch node
in jtree please help i searched but couldn't find a solution
thanx

hi i downloadeed this code from sun java tutorial
successfully changed all icons except that blue lever at extreme left of each branch node
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.ImageIcon;
import java.net.URL;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class TreeIconDemo extends JFrame {
    private JEditorPane htmlPane;
    private static boolean DEBUG = false;
    private URL helpURL;
    public TreeIconDemo() {
        super("TreeIconDemo");
        //Create the nodes.
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
        createNodes(top);
        //Create a tree that allows one selection at a time.
        final JTree tree = new JTree(top);
        tree.getSelectionModel().setSelectionMode
                (TreeSelectionModel.SINGLE_TREE_SELECTION);
         * Set the icon for leaf nodes.
         * Note: In the Swing 1.0.x release, we used
         * swing.plaf.basic.BasicTreeCellRenderer.
        DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
        renderer.setLeafIcon(new ImageIcon("yoshi.gif"));
        renderer.setClosedIcon(new ImageIcon("yoshi.gif"));
        renderer.setOpenIcon(new ImageIcon("yoshi.gif"));       
        tree.setCellRenderer(renderer);
        //Listen for when the selection changes.
        tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                   tree.getLastSelectedPathComponent();
                if (node == null) return;
                Object nodeInfo = node.getUserObject();
                if (node.isLeaf()) {
                    BookInfo book = (BookInfo)nodeInfo;
                    displayURL(book.bookURL);
                    if (DEBUG) {
                        System.out.print(book.bookURL + ":  \n    ");
                } else {
                    displayURL(helpURL);
                if (DEBUG) {
                    System.out.println(nodeInfo.toString());
        //Create the scroll pane and add the tree to it.
        JScrollPane treeView = new JScrollPane(tree);
        //Create the HTML viewing pane.
        htmlPane = new JEditorPane();
        htmlPane.setEditable(false);
        initHelp();
        JScrollPane htmlView = new JScrollPane(htmlPane);
        //Add the scroll panes to a split pane.
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(treeView);
        splitPane.setBottomComponent(htmlView);
        Dimension minimumSize = new Dimension(100, 50);
        htmlView.setMinimumSize(minimumSize);
        treeView.setMinimumSize(minimumSize);
        splitPane.setDividerLocation(100); //XXX: ignored in some releases
                                           //of Swing. bug 4101306
        //workaround for bug 4101306:
        //treeView.setPreferredSize(new Dimension(100, 100));
        splitPane.setPreferredSize(new Dimension(500, 300));
        //Add the split pane to this frame.
        getContentPane().add(splitPane, BorderLayout.CENTER);
    private class BookInfo {
        public String bookName;
        public URL bookURL;
        public String prefix = "file:"
                               + System.getProperty("user.dir")
                               + System.getProperty("file.separator");
        public BookInfo(String book, String filename) {
            bookName = book;
            try {
                bookURL = new URL(prefix + filename);
            } catch (java.net.MalformedURLException exc) {
                System.err.println("Attempted to create a BookInfo "
                                   + "with a bad URL: " + bookURL);
                bookURL = null;
        public String toString() {
            return bookName;
    private void initHelp() {
        String s = null;
        try {
            s = "file:"
                + System.getProperty("user.dir")
                + System.getProperty("file.separator")
                + "TreeDemoHelp.html";
            if (DEBUG) {
                System.out.println("Help URL is " + s);
            helpURL = new URL(s);
            displayURL(helpURL);
        } catch (Exception e) {
            System.err.println("Couldn't create help URL: " + s);
    private void displayURL(URL url) {
        try {
            htmlPane.setPage(url);
        } catch (IOException e) {
            System.err.println("Attempted to read a bad URL: " + url);
    private void createNodes(DefaultMutableTreeNode top) {
        DefaultMutableTreeNode category = null;
        DefaultMutableTreeNode book = null;
        category = new DefaultMutableTreeNode("Books for Java Programmers");
        top.add(category);
        //original Tutorial
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Tutorial: Object-Oriented Programming for the Internet",
            "tutorial.html"));
        category.add(book);
        //Tutorial Continued
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Tutorial Continued: The Rest of the JDK",
            "tutorialcont.html"));
        category.add(book);
        //JFC Swing Tutorial
        book = new DefaultMutableTreeNode(new BookInfo
            ("The JFC Swing Tutorial: A Guide to Constructing GUIs",
            "swingtutorial.html"));
        category.add(book);
        //Arnold/Gosling
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Programming Language", "arnold.html"));
        category.add(book);
        //FAQ
        book = new DefaultMutableTreeNode(new BookInfo(
            "The Java FAQ", "faq.html"));
        category.add(book);
        //Chan/Lee
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Class Libraries: An Annotated Reference",
             "chanlee.html"));
        category.add(book);
        //Threads
        book = new DefaultMutableTreeNode(new BookInfo
            ("Concurrent Programming in Java: Design Principles and Patterns",
             "thread.html"));
        category.add(book);
        category = new DefaultMutableTreeNode("Books for Java Implementers");
        top.add(category);
        //VM
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Virtual Machine Specification",
             "vm.html"));
        category.add(book);
        //Language Spec
        book = new DefaultMutableTreeNode(new BookInfo
            ("The Java Language Specification",
             "jls.html"));
        category.add(book);
    public static void main(String[] args) {
        JFrame frame = new TreeIconDemo();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
        frame.pack();
        frame.setVisible(true);

Similar Messages

  • How to desable default close icon in jtree

    how to desable default close and open icon in jtree.

    Hi,
    On Windows it is Edit>Keyboard Shortcuts...
    Create a duplicate set and disable/modify the keyboard shortcuts that you want
    Thanks!
    ps: please mark this post as Answered if this is of help to you

  • Unable to display blinking icon for JTree

    I am unable to see blinking icon for JTree node. If I use any other image which is not blinking, then I am able to see icon.
    If blinking image is used, it shows blank image.
    Please refer to following code.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.net.URL;
    import javax.swing.ImageIcon;
    import javax.swing.JApplet;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class TreeApplet extends JApplet {
    JTree tree;
    DefaultMutableTreeNode root;
    DefaultMutableTreeNode node1;
    DefaultMutableTreeNode node2;
    DefaultMutableTreeNode node3;
    DefaultMutableTreeNode node4;
    private ImageIcon errorIcon = null;
    private URL resource = null;
    private static final long serialVersionUID = 1L;
    public void init() {
         errorIcon = loadIcon("images/errorBlink.gif");
         root = new DefaultMutableTreeNode(new ProcessInfo("root", "error"));
         node1 = new DefaultMutableTreeNode(new ProcessInfo("Node1", "info"));
         node2 = new DefaultMutableTreeNode(new ProcessInfo("Node2", "warn"));
         node3 = new DefaultMutableTreeNode(new ProcessInfo("Node3", "debug"));
         node4 = new DefaultMutableTreeNode(new ProcessInfo("Node4", "error"));
         node1.add(node2);
         node3.add(node4);
         root.add(node1);
         root.add(node3);
         setLayout(new BorderLayout());
         tree = new JTree(root);
         tree.setCellRenderer(new TreeRenderer());
         add(new JScrollPane((JTree) tree), "Center");
    private class TreeRenderer extends DefaultTreeCellRenderer {
         private static final long serialVersionUID = 1L;
         public TreeRenderer() {
              this.setBackgroundSelectionColor(Color.lightGray);
              this.setBorderSelectionColor(Color.BLACK);
         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);
              setIcon(getStatus(value));
              return this;
         private ImageIcon getStatus(Object value) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
              ProcessInfo nodeInfo = (ProcessInfo) node.getUserObject();
              String status = nodeInfo.getStatus();
              if ( status != null ) {
              if ( status.equalsIgnoreCase("error") ) {
                   return errorIcon;
              return null;
    private ImageIcon loadIcon(String name) {
         ImageIcon icon = null;
         resource = this.getClass().getResource(name);
         if ( resource != null ) {
              icon = new ImageIcon(resource);
         return icon;
    }

    1. Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    2. A renderer is just a "rubber stamp" used to paint on the table/tree/list/whatever. You can't display animation in an ImageIcon by setting it to a renderer. Since the JLabel subclass used as the renderer isn't a part of any visible component hierarchy, the icon won't be refreshed with new frames.
    db

  • How to Use different icons for JTree in the same level

    Hi guys, i come cross a problem with JTree. The module need a JTree which need to represent items in the same level using different icons. For example:
    [Icon for Root]Root
    |
    |_____________[Icon for Table] TABLES
    |
    |_____________[Icon for Index] INDEXS
    |
    |_____________[Icon for Views] VIEWS
    As i know, the default behavior for JTree is using the same icon for all leaves and
    the same icon for all node that has children. How can i achieve that?
    Thansk a lot!

    subclass DefaultTreeCellRenderer. if you overwrite the method below, then you can set the icon to whatever you want....!
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                    boolean sel,
                                    boolean expanded,
                                    boolean leaf, int row,
                                    boolean hasFocus) {
         String         stringValue = tree.convertValueToText(value, sel,
                               expanded, leaf, row, hasFocus);
            this.tree = tree;
         this.hasFocus = hasFocus;
         setText(stringValue);
         if(sel)
             setForeground(getTextSelectionColor());
         else
             setForeground(getTextNonSelectionColor());
         // There needs to be a way to specify disabled icons.
         if (!tree.isEnabled()) {
             setEnabled(false);
             if (leaf) {
              setDisabledIcon(getLeafIcon());
             } else if (expanded) {
              setDisabledIcon(getOpenIcon());
             } else {
              setDisabledIcon(getClosedIcon());
         else {
             setEnabled(true);
             if (leaf) {
              setIcon(getLeafIcon());
             } else if (expanded) {
              setIcon(getOpenIcon());
             } else {
              setIcon(getClosedIcon());
            setComponentOrientation(tree.getComponentOrientation());
         selected = sel;
         return this;
        }

  • Using animation as icon for JTree node

    Hi,
    I am using a custom tree cell renderer. I have a label in the renderer, the label have gif Image Icon, but the problem is it is not getting animated. But when I use a JLabel with gif icon some where else it is working fine, but it is not working for tree node.
    package com.gopi.utilities.gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeCellRenderer;
    import com.gopi.remfilebrowser.gui.GUIUtil;
    import com.gopi.remfilebrowser.util.FileBrowserConstants;
    public class CustomTreeCellRenderer implements TreeCellRenderer
         private JPanel panel;
         private JLabel label;
         private TreeCellRenderer defaultRenderer;
         public CustomTreeCellRenderer()
              super();
              panel = GUIUtil.createGridBagPanel();
              label = new JLabel();
              label.setHorizontalAlignment(JLabel.LEFT);
              System.out.println("New");
              GridBagConstraints gc = new GridBagConstraints();
              GUIUtil.fillComponent(panel,label);
              defaultRenderer = new DefaultTreeCellRenderer();
         public Component getTreeCellRendererComponent(JTree tree, Object value,
                     boolean sel,
                     boolean expanded,
                     boolean leaf, int row,
                     boolean hasFocus)
              if(value instanceof NewAbstractTreeNode)
                   NewAbstractTreeNode node = (NewAbstractTreeNode) value;
                   System.out.println("dr");
                   label.setText(value.toString());
                   label.setIcon(ImageLoader.getInstance().getIcon(node.getIconKey()));
                   if(hasFocus && sel)
                        panel.setBackground(FileBrowserConstants.TREE_NODE_SELECTED_COLOR);
                   else if(sel)
                        panel.setBackground(FileBrowserConstants.TREE_NODE_UNSELECTED_COLOR);
                   else
                        panel.setBackground(Color.white);
                   return panel;
              return defaultRenderer.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
    }

    JLabels using ImageIcons are designed to display the icon as is, including animation and all.
    A CellRenderer only paints the Icon once, when the cell is painted. Much ike a rubber stamp of the JComponent. Hence, its not designed to do the animation and all.
    If you really want it, you can probably use MediaTracker and a Timer to do your animation scheduling. Might not be very pretty code though
    ICE

  • Icons and JTree

    Hi,
    How can I produce my own icons to appear next to nodes in a JTree. At the moment I am using gifs I got elsewhere, but I want to design my own for custom display.
    Thanks for any help,
    Claire

    here you are to replace the cirle or plus icon with icons homemade
    ^  ComponentUI ui = tree.getUI();
              if (ui instanceof BasicTreeUI) {
                   ((BasicTreeUI)ui).setExpandedIcon(new ImageIcon(images.getString("TREEMIN")));
                   ((BasicTreeUI)ui).setCollapsedIcon(new ImageIcon(images.getString("TREEPLUS")));
    [\code]
    greetings Sven                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem setting icon in jtree

    I have read the tutorial but i still cant get a home made icon in my tree-component. If i load it and teel to use it it doesn't show!!! what's wrong??
    public DefaultMutableTreeNode
                tnRoot = new DefaultMutableTreeNode("FleetCommander"),
                tnFree = new DefaultMutableTreeNode("Vessels Free to Use");
            DefaultTreeModel tmInfo = new DefaultTreeModel(tnRoot);
        JTree tInfo = new JTree(tmInfo);
        JScrollPane spInfo = new JScrollPane(tInfo);
        ImageIcon Icons[] = new ImageIcon[20];
        JALOCTreeCellRenderer tcr;
        public DisplayMap(Object par, DefaultMap m) {
            parent = par;
            this.m = m;
                // ControlPanel
            f2.setSize(300,400);
            f2.setLocation(700,10);
            Container p = f2.getContentPane();
            tnRoot.add(tnFree);
            ToolTipManager.sharedInstance().registerComponent(tInfo);
            Icons[0] = new ImageIcon("Images/jaloc_fc_main_icon.gif");
            tcr = new JALOCTreeCellRenderer(Icons, this);
            tInfo.setCellRenderer(tcr);
            p.add(tInfo,BorderLayout.CENTER);
            f2.setVisible(true);
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class JALOCTreeCellRenderer extends DefaultTreeCellRenderer {
        Icon Icons[];
        DisplayMap disp;
        public JALOCTreeCellRenderer(Icon[] icons, DisplayMap dm) {
            this.Icons = icons;
            this.disp = dm;
        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 (disp.tnRoot.equals(value)) {
                setIcon(Icons[0]);
                setToolTipText("This book is in the Tutorial series.");
            } else {
                setToolTipText(null); //no tool tip
            return this;
    }

    Yes that functions fine.Hm, I'm not completely awake yet ;-) but I checked with my own code
    and the only difference I see is that I return what the super call had
    returned; something like this: Component result= super.getTreeCellRendererComponent(
                            tree, value, sel,
                            expanded, leaf, row,
                            hasFocus);
            if (disp.tnRoot.equals(value)) {
                setIcon(Icons[0]);
                setToolTipText("This book is in the Tutorial series.");
            } else {
                setToolTipText(null); //no tool tip
            return result;Give it a try ...
    kind regards,
    Jos

  • Adding JCheckbox as icon to JTree Nodes

    Hi,
    I need to provide a GUI for something like instllation shield. The application shows a list of modules and sub modules in a tree format. Users can select any sub modules for installation, using a checkbox ( located at icon space of a JTree, if possible ).
    The checkbox at each module indicates (i) All sub modules are selected, (ii) All sub modules are deselected, (iii) Partial selection.
    Is it possible? How to do that?
    Please help me out!
    Prashant

    Oh thank you.
    I found the stuff on the link you gave. It is helpful eventhough code is not availabale. I am planning to write the code by implementing necessary interfaces.
    Thanks again,
    Prashant

  • How do I remove expand / collapse icon for JTree empty folders

    Hi
    I am using a JTree as a file system browser. I use DefaultMutableTreeNode nodes.
    I have a problem with empty folders.
    Empty folders show the expand / collapse icon, leading the user to believe there are sub-directories. When the user double-clicks the folder, the expand / collapse icon goes away. This is a "haha-gotcha" glitch that I really don't want my users to have to continually deal with.
    So, how might I get my JTree to not show the expand / collapse icon for empty folders?
    Thanks
    Wayne

    Maybe I can use the FileSystemView isTraversable(File f) method in my TreeCellRenderer class to check if anything is in the directory.
    But I still need to know how to disable the expand / collapse icon for such a node.

  • How to set icon for JTree

    hi,
    I have a JTree. For this JTree i have a DefaultJTreeCellRenderer.
    i have done like this
    JTree tree = new JTree();
    DefaultJTreeCellRenderer renderer = new DefaultJTreeCellRenderer();
    renderer.setOpenIcon(....);
    renderer.serCloseIcon(...);
    tree.setCellRenderer(renderer);but this is not working.
    how to change the icons of the node when i click
    thank you

    public class Test extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         private JButton buttonCreate;
         private JTree tree;
         private DefaultMutableTreeNode defaultMutableTreeNode;
         private DefaultTreeModel defaultTreeModel;
         private int i;
         public Test() {
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              layoutComponents();
              setSize(400, 400);
              setLocationRelativeTo(null);
              setVisible(true);
         private void layoutComponents() {
              defaultMutableTreeNode = new DefaultMutableTreeNode("Root");
              defaultTreeModel = new DefaultTreeModel(defaultMutableTreeNode);
              tree = new JTree(defaultTreeModel);
              tree.setRootVisible(false);
              buttonCreate = new JButton("Create");
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(tree, BorderLayout.CENTER);
              getContentPane().add(buttonCreate, BorderLayout.SOUTH);
              DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
              ImageIcon icon_close = new ImageIcon("./images/project_closed.gif");
              ImageIcon icon_open = new ImageIcon("./images/project_opened.gif");
              renderer.setOpenIcon(icon_open);
              renderer.setClosedIcon(icon_close);
              tree.setCellRenderer(renderer);
              buttonCreate.addActionListener(this);
         public static void main(String[] args) {
              new Test();
         public void actionPerformed(ActionEvent e) {
              addElementToParent("Child" + i++);
         private DefaultMutableTreeNode addElementToParent(Object theChild) {
              return addElementToParent(defaultMutableTreeNode, theChild, true);
         private DefaultMutableTreeNode addElementToParent(DefaultMutableTreeNode theParent, Object theChild, boolean shouldBeVisible) {
              DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(theChild);
              if (theParent == null) {
                   theParent = defaultMutableTreeNode;
              defaultTreeModel.insertNodeInto(childNode, theParent, theParent.getChildCount());
              TreePath childTreePath = new TreePath(childNode.getPath());
              //          Make sure the user can see the lovely new node.
              if (shouldBeVisible) {
                   tree.scrollPathToVisible(childTreePath);
              tree.requestFocusInWindow();
              return childNode;
    }this is the code which i was trying to execute.
    here i want to explain you is
    when i click the node the icon should change to open_icon
    when i click the other node the previous node icon should change to close_icon
    how is this possible
    null

  • Change behaviour of Expand/collapse icon in JTree

    Want to change the behaviour of Expand/collapse icon in a JTree. Need help with the same. Thanks.

    Check: Hide and show region

  • Possibility to have your own icons in JTree depending on what node

    Can you specify your own icons in a JTree? With this I mean more than your own directory/leaf icons. For example, if you have a family tree, you might want different icons for sons and daugthers etc.

    I did like you said, and it works, almost.
    I use the following code to find out what type my nodes in the tree are. I can just look at my NodeInfo object to get that. But when I click at different nodes in the tree, other nodes than the clicked one changes icons.
    DefaultMutableTreeNode node =
                   (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
              NodeInfo selectedNode = (NodeInfo)node.getUserObject();Edit: Also tried this code but that gave me:
    Exception in thread "main" java.lang.ClassCastException: java.lang.String
         at gui.MyTreeCellRenderer.getTreeCellRendererComponent(MyTreeCellRenderer.java:26)
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              NodeInfo selectedNode = (NodeInfo)node.getUserObject();Message was edited by:
    sandsater

  • Icon on Jtree

    Hi, i need chance the icon when i select one item from my JTree ex.
    -root
    + Panel 1
    - Label 1
    - Edit 1
    + Panel 2
    - Label 2
    - Edit 2
    when i click on LABEL 2 i need to change de ICON From LABEL 2 if i click on PANEL1 i need to chance de icon from PANEL 1, LABEL 1 and EDIT 1
    tanks

    Using a renderer is the right way to go
    If you can post your code we can help you in fixing it
    Thanks,
    Shrimon

  • Icons on JTree

    Hi...
    In my JTree, I have two class (that extend DefaultMutableTreeNode) that can be leaf. I want to set different Icons for each one of the class. How do I do that? Below, the code I tryed, it does not work (the icons change, but sometimes they are associated with the wrong class).
    public class VRTreeCellRenderer extends DefaultTreeCellRenderer {
        public Component getTreeCellRendererComponent (JTree tree, Object value,
                boolean selected, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, selected, expanded,
                    leaf, row, hasFocus);
            if (value.getClass() == DefaultPort.class) {
                this.setLeafIcon(new ImageIcon (MainApp.gifIconPath + "door.gif"));
            } else if (value.getClass() == Stream.class) {
                this.setLeafIcon(new ImageIcon (MainApp.gifIconPath +
                        "corrente.gif"));
            return this;
    }

    Gack!!!
    Don't go loading and creating images inside this method, it's done on the paint loop and you'll slow it down. Load your images up front and store them as field in the object.
    Don't use "foo.getClass() == Bar.class" to compare classes, use "foo instanceof Bar" - otherwise you can fall over if multiple class loaders are used.
    Don't throw away the value returned by the superclass method, use it. You discard it and then return "this" - which in actual fact works fine as you know, but semantically it's wrong and if the implementation of the default renderer changes then your code breaks.
    Also, by the time you set the icon it's too late. The superclass has already configured the component for the cell in question; you are in fact configuring it for the next time it passes through. So, move those methods above your call to the superclass method.

  • Individual leaf icons in JTree

    is it possible to for different leaves in the same tree to have different icons?
    I tried this code:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Actors");
            File dir = new File("images\\actors\\");
            int i = 0;
            DefaultMutableTreeNode actorChild;
            String[] fileArray = dir.list();
            while (i < dir.listFiles().length){
                ImageIcon icon = new ImageIcon(getClass().getResource("images\\actors\\" + fileArray));
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
    renderer.setLeafIcon(icon);
    actorChild = new DefaultMutableTreeNode(fileArray[i]);
    root.add(actorChild);
    i++;
    actorTree.setCellRenderer(renderer);
    DefaultTreeModel t = new DefaultTreeModel(root);
    actorTree.setModel(t);
    However as you can see it merely sets all leaf icons to the last  value from the last iteration of the loop.
    any info appreciated :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    This is my latest attempt, but it still doesnt work, it just makes the icon for the last item in the jtree.
    I cant figure out what im doing wrong here, any ideas?
    class CustomIconRenderer  extends JLabel implements TreeCellRenderer {
        String[] fileArray;
        CustomIconRenderer(String[] fileArray){
            this.fileArray = fileArray;
        public Component getTreeCellRendererComponent(JTree tree,
                Object value, boolean sel, boolean expanded, boolean leaf,
                int row, boolean hasFocus) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            Object obj = node.getUserObject();
            String nodeName = obj.toString();
            setText(nodeName);  // set the text
            int i = 0;
            while (i < fileArray.length){
              if (nodeName.endsWith(fileArray)){
    Icon icon = new ImageIcon(getClass().getResource("images\\actors\\"+ nodeName));
    setIcon(icon);
    else{
    setIcon(null);
    i++;
    return this;

Maybe you are looking for