JTree leaf icon

Hi,
I am doing a sort of explorer, with a JTree.
I know how to change icons for leafs, but sometimes my leafs are indeed branches but without nothing in it (an empty directory).
so the tree displays it as a leaf. But I would like that the tree displays it with the directory icon (but without the "+" sign).
How can i do this ?
Sylvain.

I haven't such problems...
Ok. You have to create your custom TreeCellRenderer and set it to the tree.
IconRenderer myRenderer=new IconRenderer ();
tree.setCellRenderer(myRenderer);
class IconRenderer extends JLabel implements TreeCellRenderer
public Component getTreeCellRendererComponent(JTree tree,
          Object value, boolean sel, boolean expanded, boolean leaf,
          int row, boolean hasFocus)
setText(value.toString());
//process value (value represents you tree node content)
if (!leaf) {
if (expanded)
setIcon(new ImageIcon("images/expanded.gif"));
else
setIcon(new ImageIcon("images/collapsed.gif"));
else {
setIcon(new ImageIcon("images/text.gif"));
MyObject myObj=(MyObject)value;
if (myObj.isBranch()) {
setIcon(new ImageIcon("images/branch.gif"));
regards
Stas

Similar Messages

  • JTree Update Leaf Icon

    Hi,
    I have two problem with Jtree.
    1.How can I put different Icons for different leafs of the same node?
    2.How is it possible to refresh or update the Jtree(by adding or removing some leaf) that the leaf Icons remain?
    Thanks for your help.

    1.How can I put different Icons for different leafs of the same node?Yes, ... either write a custom cell renderer or find a "merged icon".. there are examples of both around the forums.
    2.How is it possible to refresh or update the Jtree(by adding or removing
    some leaf) that the leaf Icons remain?No. if you remove a node, the node is gone. If you don't remove the node, the node stays. IF you want to leave the leaf icon, you can have a renderer which just displays the icon and not the text.

  • 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;

  • How to change leaf icon in jtree

    Hi,
    I have one treeviewer class in which i have set the leaf icon like
    renderer1.setLeafIcon(new ImageIcon(RMViewer.getApplication().getIconImageManager().getImage("TRMA")));
    it's working fine..i have one more class namely IntFrame....there i have one button which display some doc...now when i click on button i wanna change only selected leaf icon not other leaf icon...
    how do i proceed...can u provide me some examples
    regards
    Tarique

    Can u provide me the some source code...
    i m not able to do this..
    Regards
    Tarique

  • How to remove folder and leaf icons from a tree

    Hi,
    I know how to remove when we have a mx component i.e.,
    <mx:Tree folderOpenIcon={null} ...../> similarly for
    closed and default leaf icon.
    But how do i achieve this from an action script like say i
    have,
    var tree:Tree = new Tree();
    tree.setFolderOpenIcon(null); ///is there something like this
    or any other alternative.
    Please advice.
    Thanks,
    Lucky

    the folderOpenIcon is a style so you have to set it with the
    setStyle method
    try:
    tree.setStyle("folderOpenIcon",null);

  • Right mouse button click in a JTree leaf

    Hi,
    how can I add a mouse listener in a JTree leaf? I have DOM nodes wrapped and a JTree model adapter to set up the JTree. I want the popup menu to show everytime the user clicks on a leaf, but not on the tree itself.
    Thanks!

    Really you just have to add your listener to the tree itself, then use the Point to find the corresponding TreePath (getPathForLocation), from which you'll easily find the node.

  • Tree.leafIcon for leafIcon.  How about non-leaf Icon?

    Tree.leafIcon for leafIcon. How about non-leaf Icon?
    Where can find it, the non-leaf icon (folder -- look)
    to be used for some other place?

    Your welcome for the help you got when you posted your original question:
    http://forum.java.sun.com/thread.jspa?threadID=5204746
    Since you didn't appreciate the help, I won't botheri replying to this question.
    Besides this question is asked all the time in the forum, so if you do some searching you can find the answer.

  • JTree rendering extra node and leaf icons at the end of the label

    Hi,
    Does anyone know how to add an icon to a JTree node or leaf in such a way that it will be displayed behind the text label?
    In an example:
    - rootnode
    - childnode [icon]
    |- leaf
    + childnode [icon]
    Where -/+ are the default (un)collapse icons
    I'd like to apply this to show additional information by using icons with respect to a node.
    I couldn't find anything on the net besides changing the default open/close node icons, yet that's not what I'm aiming for here.

    use this one.I think it will help u.Gd lk
    tree =new JTree(root);
    DefaultTreeCellRenderer renderer =(DefaultTreeCellRenderer)tree.getCellRenderer();
    renderer.setLeafIcon(new ImageIcon(getClass().getResource("leafimages/3.gif")));
    renderer.setClosedIcon(new ImageIcon(getClass().getResource("leafimages/1.gif")));
    renderer.setOpenIcon(new ImageIcon(getClass().getResource("leafimages/2.gif")));
    renderer.setBackgroundNonSelectionColor(new Color(15,85,134));
    renderer.setBackgroundSelectionColor(Color.YELLOW);
    renderer.setTextNonSelectionColor(new Color(217,227,227));
    renderer.setTextSelectionColor(Color.RED);
    renderer.setHorizontalTextPosition(SwingConstants.LEADING);
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    tree.setFont(new Font("Tahoma",1,12));
    tree.setBackground(new Color(15,85,134));

  • Jtree Select node and change leafs icon problem

    Hi All,
    i create a tree and implement a TreeSelectionListener:
    my mission is whenever i select a node i need to change the icon of this node (for now.later i will have to find if it have childrens).
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    public class TreeView{
         DefaultMutableTreeNode top;
         JTree tree ;
         Color frameColor;
         public static ImageIcon NoTSelIcon;
         public static ImageIcon SelIcon;
        public static String[] name= new String[8];
         public TreeView(Color BackColor) {
              // TODO Auto-generated constructor stub
            top =  new DefaultMutableTreeNode("Diagnostics");
            this.frameColor=BackColor;
             SelIcon = createImageIcon("../Resource/Images/Select.gif");
             if (SelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
             NoTSelIcon = createImageIcon("../Resource/Images/NotSelc.gif");
               if (NoTSelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
         public Component createTreeComponents(){
                //Create the nodes.
                 createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            //TREE LISTENERS
            //Treeselction listener
            Handler hObject = new Handler();
            tree.addTreeSelectionListener(hObject);
           //Tree expand/collapse listener
            HandlerExpansionListener hObjectExpan = new HandlerExpansionListener();
            tree.addTreeExpansionListener(hObjectExpan);
    //       tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
            //set tree background
            tree.setBackground(frameColor);
             tree.setCellRenderer(new OverrideTreeCellRenderer(frameColor,SelIcon,NoTSelIcon));
            return tree;
          private void createNodes(DefaultMutableTreeNode top) {
                 DefaultMutableTreeNode category = null;
                 DefaultMutableTreeNode SubCategory = null;
                 DefaultMutableTreeNode SubCategoryBasee = null;
                 DefaultMutableTreeNode SubSubCategoryBasee = null;
                 category = new DefaultMutableTreeNode("Dfe");
                 top.add(category);
                 //Sub test visible
                 SubCategory = new DefaultMutableTreeNode("Test Visible");
                 category.add(SubCategory);
                 SubCategory.add(new DefaultMutableTreeNode("Son 1"));
                 SubCategory.add(new DefaultMutableTreeNode("Son 2"));
                 SubSubCategoryBasee = new DefaultMutableTreeNode("Test Base");
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 1"));
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 2"));
                 SubCategory.add(SubSubCategoryBasee);
          class Handler implements TreeSelectionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeSelect event ");
                        TreePath trph;
                        trph=arg0.getNewLeadSelectionPath();
                        int count=trph.getPathCount();
                        DefaultMutableTreeNode Selnode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                        String Name = (String)Selnode.getUserObject();
                        setSelected(Selnode,true);
                        int number_ofnodes=getNodeCountBelow((TreeModel)tree.getModel() , Selnode, false);
                        System.out.println("The Number of nodes under "+Name+"="+number_ofnodes);
                        tree.setCellRenderer(new IconRenderer(SelIcon,NoTSelIcon,frameColor));
          class HandlerExpansionListener implements TreeExpansionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)  tree.getLastSelectedPathComponent();
                        if (node == null) return;
                      }     // The inner class
                   public void treeCollapsed(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeCollapsed event ");
                   public void treeExpanded(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeExpanded event ");
          /** Returns an ImageIcon, or null if the path was invalid. */
             protected static ImageIcon createImageIcon(String path) {
                  //ImageIcon imcon= new ImageIcon(path);
                  //return imcon;
                 java.net.URL imgURL = TreeView.class.getResource(path);
                 if (imgURL != null) {
                     return new ImageIcon(imgURL);
                 } else {
                     System.err.println("Couldn't find file: " + path);
                     return null;
             DefaultMutableTreeNode newnode;
             public void setSelected(DefaultMutableTreeNode Selnode ,boolean isSelected)
                    Enumeration Enchilds=Selnode.children();//ENUMRATE ALL CHILDS FOR THIS NODE
                 if (Enchilds != null)
                      while (Enchilds.hasMoreElements())
                           newnode=(DefaultMutableTreeNode)Enchilds.nextElement();
                           String NameSel = (String)newnode.getUserObject();
                           setSelected(newnode,isSelected);
             //GETTING THE TREE DEPTH
             public int getNodeCountBelow(TreeModel model, Object node, boolean includeInitialNode)
                 int n = includeInitialNode ? 1 : 0;
                 for (int i = 0; i < model.getChildCount(node); i ++)
                     n += getNodeCountBelow(model, model.getChild(node, i), true);
                 return n;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import javax.swing.Icon;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class IconRenderer extends DefaultTreeCellRenderer {
         private static final long serialVersionUID = 1L;
         Icon SelectedIcon;
         Icon NotSelectedIcon;
         Color BackgroundColor;
         boolean Selected=false;
         boolean Leaf=false;
         boolean IsItaChild=false;
         DefaultMutableTreeNode SelctedNode=null;
        public IconRenderer(Icon SelIcon,Icon NoTSelIcon,Color Bacground) {
             SelectedIcon = SelIcon;
             NotSelectedIcon = NoTSelIcon;
             BackgroundColor=Bacground;
             setBackgroundNonSelectionColor(BackgroundColor);
        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);
             Selected=sel;
             Leaf=leaf;
             DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
             String s2 = (String)node.getUserObject();
       return this;
    }my problem is :
    when i select a node the the method "getTreeCellRendererComponent"
    start to run on the entire tree from buttom to top and than from top to buttom.
    for me it waste of time because if has say 100 nodes it wont botthers me.
    but i have 20000 nodes and more its take a time.
    and for all this nodes i have to make compares.
    is there a way to force the DefaultTreeCellRenderer to not run the entire tree???
    Thanks

    You need to make sure that your TreeModel interprets your group nodes to be non-leaf nodes (one of the methods in the TreeModel interface is called isLeaf). If you are using a DefaultTreeModel with DefaultMutableTreeNode objects, you can use the askAllowsChildren property of DefaultTreeModel and the allowsChildren property of DefaultMutableTreeNode to control this. See the API for more details:
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html

  • Jtree leaf custom icons

    I created my own class that extands DefaultTreeCellRenderer and overrided the function getTreeCellRendererComponent.For now I see the customed icon on the leaf,but when I touch with the mouse the panel the vision of the leaf comes back to default.I tried to do repaint it's doesn't help me
    May be you have any suggestions?

    ok I did the following code in a previous project to handle a similer requirement
    It s from a large project so I'll only post a small part and hope that you can understand it
    If you dont just let me know which part
    package lrmk.client.nav;
    import lrmk.client.*;
    import lrmk.client.wnd.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import javax.swing.*;
    public class NavCellRenderer implements javax.swing.tree.TreeCellRenderer
       DefaultTreeCellRenderer form_window  =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer dialog_box   =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer table_window =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer custom =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer def  =  new DefaultTreeCellRenderer();
       public NavCellRenderer(){
          form_window.setLeafIcon(ClientGlobals.getImageIcon("lrmk/client/images/form_icon.gif"));
          dialog_box.setLeafIcon(ClientGlobals.getImageIcon("lrmk/client/images/dialog_icon.gif"));
          table_window.setLeafIcon(ClientGlobals.getImageIcon("lrmk/client/images/table_icon.gif"));
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          TreeCellRenderer r = def;
          NavNode nn = null;
          if (value instanceof NavNode)
             nn = (NavNode)value;
          if (nn != null && nn.getIcon() != null)
             r = custom;
             custom.setLeafIcon(nn.getIcon());
          else if (value instanceof WindowNavNode)
             WindowNavNode wnn = (WindowNavNode)value;
             if (CDialogBox.class.isAssignableFrom(wnn.getWndClass()))
                r = dialog_box;
             else
                String name = wnn.getWndClass().getName();
                name = name.substring(name.lastIndexOf("."));
                if (name.startsWith(".Frm"))
                   r = form_window;
                else if (name.startsWith(".Tbw"))
                   r = table_window;
          return r.getTreeCellRendererComponent(tree,value,selected,expanded,leaf,row,hasFocus);
    }

  • JTree node icon adnd leaf icons

    Need Help.......
    Need to change icon in the root node and leaf ; but they must be different each other . Trying to use a renderer but change every leaf with same icon .same happend to nodes.
    Thanks a lot

    have you gone through this
    [tree display|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display]
    and also try searching the forum there are lot more similar post.

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • JTree custom icon help

    Hi, i am trying to get custom icon for specific nodes of a tree. In my customTreeCellrenderer that extends the default predecessor, i have this function. The problem is that, the icons are not set to the node i want but the node after that node. Anyone got any suggestions as to what i am doing wrong ?
    Thanks, Dave
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
              ImageIcon error = new ImageIcon("illegal.gif");
              super.getTreeCellRendererComponent(tree, value, sel,expanded, leaf, row,hasFocus);
              DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
              GroupNodeObject obj = (GroupNodeObject) node.getUserObject();
              if(node.getUserObject() instanceof GroupNodeObject){
                   if(obj.isIllegal()){
                        this.setLeafIcon(error);
                        this.setClosedIcon(error);
                        this.setOpenIcon(error);
                   }else{
                        this.setLeafIcon(getDefaultLeafIcon());
                        this.setClosedIcon(getDefaultClosedIcon());
                        this.setOpenIcon(getDefaultOpenIcon());
              return this;
         }

    may be the next node is instance of GroupNode!!
    just incase, check the code if the error is assigning the nodes!
    This code looks ok.

  • JTree Node Icons

    Ok i know how to set a icon for all nodes in a JTree but my problem is setting incons for certain nodes. I am trying to Create a UML Training Tool for my degree and i have major trouble here. I can change the icons for all but all i want to do is change them for individual nodes, for example a different icon for an actor to a use case, please please can someone help this beginner.

    You need to subclass DefaultTreeCellRenderer and override the getTreeCellRendererComponent method, like:
    class CustomRenderer extends DefaultTreeCellRenderer {
      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 (whatever) setIcon(myIcon);
    }                 Then set the cell renderer for your tree:
    myTree.setCellRenderer(new CustomRenderer());

  • JTree - Parent Icon for children

    Hello,
    I have a JTree that displays Categories (=Parent) and it's content (=Child):
    Cat 1
    Cat 2
    Content 1
    Cat 3
      Cat 3.1
        Content
    ...There are some categories that do not have children, and so their icon is the same as the leaves's icon.
    How can I change the icon of categories who do not have children to a "parent-icon"?
    thanks,

    Inherit DefaultTreeCellrenderer and override getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus). Now you can set the icons individually.
    Tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

Maybe you are looking for