JTree leaves Icons

I would like to set the leaves icon of a JTree.
I used a DefaultTreeCellRenderer and the method setLeafIcon.
What i want to do is set two different icons for two different kind of leaf ....
is it possible ?????
Thanks.

Yes, that's possible.
I would recommend the following:
a) derive you renderer from DefaultTreeCellRenderer (you probably know this already);
b) in its main method getTreeCellRendererComponent() call the super implementation (super.getTreeCellRendererComponent());
c) use given parameters to determine the kind of tree node the renderer is going to 'paint' on the screen (parameters 'value', 'leaf');
d) access your data structures (or whatever you plan to have) to find out the kind of Icon you want to set for that tree node;
e) call method setIcon() of your renderer class. As it is derived from JLabel, it shall understand this call correctly.
You are done.

Similar Messages

  • JTree changing Icons of leaves of a node

    I have a Jtree with root node as "Project"
    I have nodes as "color", "sports", "food" which in turn have leaves.
    I have to set an Icon "Icon1" for all the leaves of node "color"
    I have to set another Icon "Icon2" for all leaves of node "sports"
    and have to set another Icon3" for all the leaves of node "food"
    How do I go about doing it? Thanks.

    Take a look at the Swing Tutorial, specifically http://web2.java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display. This gives a straightforward example of changing icons (or anything on the node) by using a cell renderer.

  • 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

  • JTree customization icons

    Hello,
    Introduction:
    The hierarchical model is a part of the reality, a lot of real examples could be implemented, however the difficulty is to make the nodes of the Jtree closer as possible to the real model.
    My needs:
    1\I need a JTree which should executed as applet.
    2\the top , the branches, and the leaves should customizable.(I would like to have a special icons for each)
    3\when clicking the user should have a data from a java servlet throught tomcat according to each node.
    4\Internationnalization.
    The actual situation:
    1\I have the tree which executes as applet,
    2\I can customize the leaf only by asigning an icon, according to displayed text for the leafe!!!!!!!!!:(
    what about the top of the tree and the branches?
    also, that will be a reall problem when I will try to make an internationnalization!, isn't it?
    so I need a way to make a difference for displayed text and something like an identificator for the tree.
    3\When clicking a tree node the action is to launch an url for a servlet whith passing the displayed text in the tree as a parameter, then the servlet will display the corresponding document(jsp).
    as it's explained in 2\ that will be a real problem when internationnalizing.
    My Questions:
    1\Is there any way the customize all the icons in a tree?, one by one...
    2\Is it possible to refer to a node with an identificator?, as an internal identificator for the programme.And of course the displayed text will different?
    3\Please, provide my with some working codes sources.
    Thanks and Regards,
    kifwet

    Hi,
    I was working on tree icons last week. I used a tree renderer.
    Something like that :
    JTree tree;
    tree.setCellRenderer(new MyRenderer());
    private class MyRenderer extends DefaultTreeCellRenderer {
              Icon treeCollapsedIcon;
              Icon treeExpandedIcon;
              Icon leafIcon;
              public MyRenderer() {
                   super();
    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 ) {
                   setIcon(leafIcon);
                   } else {
                        if (expanded) {
                   setIcon(treeExpandedIcon);
                   }else{
                        setIcon(treeCollapsedIcon);
         return this;
    I hope this will help you
    Zauz

  • 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 + Setting Icon

    I have created a JTree that works fine. I wonder If there is a way of changing the tree icon of a specific leaf when I selected (Only that particular leaf). I tried few things with TreeRenderer but the best done was that I managed to change all the leaf.
    Thank you for your help.

    Use a TreeCellRenderer instead. It has a parameter that tells you whether the cell is selected, so you can assign a different icon based on that parameter.

  • JTree cropping icons...

    Hi, I have a set of 22x22pixel icons that I am displaying in a JTree. At this size however, the icons are having 2-4 pixels cropped off of them by the renderer. I have tried overriding the (s|g)etMinimumSize() methods of DefaultTreeCellRenderer, but to no avail. Does anyone have any advice, or a solution to this problem.
    Many thanks.

    Try
    import javax.swing.plaf.basic.BasicTreeUI;
    ((BasicTreeUI)myTree.getUI()).setRightChildIndent(SOME_NUMBER);
    ((BasicTreeUI)myTree.getUI()).setLeftChildIndent(SOME_OTHER_NUMBER)

  • 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

  • JTree control icons. How do I get rid of those suckers?

    Okay, so I'm using a JTree cldonkey (you can't say class, so please replace every occurence of cldonkey with the correct word, and please use it instead of class, I think it's funny, even though you don't), and I HATE those stupid little circles. How can I replace them with my own icon? I've found the MetalIconFactory. Do I do it in there? I wish I knew, then I would die happy, in a few decades.

    Try using the UIManager to change the default icons:
    UIManager.put( "Tree.openIcon", yourOpenIcon );
    UIManager.put( "Tree.closedIcon", yourClosedIcon );For a list of all properties of the JTree component as well as all other components, check out this program:
    http://www.discoverteenergy.com/files/ShowUIDefaults.java

  • JTree Expanded Icon

    How can I change the icon in the JTree of JavaHelps TOC when I expand or close the node. I understand that I need to give the tree a different cell renderer but can't find out where to do that. Does anyone have an example of this?
    Thanks,
    Rich
    Developer

    Thankyou for your help. I am getting a lot closer. There is something I am still missing though. I am sure I am setting the cell renderer to the tree now. The problem is that it is not effecting the images at all. Here is my code for this. Can you see what I am doing wrong?
    private void jButtonHelp_ActionPerformed()
              try
                   ClassLoader loader = this.getClass().getClassLoader();
                   URL helpURL = HelpSet.findHelpSet(loader, "helpset.hs");
                   m_hs = new HelpSet(loader, helpURL);
                   HelpBroker hb = m_hs.createHelpBroker();
                   JHelp jhelp = new JHelp(m_hs);
                   JHelpTOCNavigator jhtoc = null;
                   hb.setDisplayed(true);
                   new CSH.DisplayHelpFromSource(hb);
                   for(Enumeration enum = jhelp.getHelpNavigators();enum.hasMoreElements();)
                        try
                             jhtoc = (JHelpTOCNavigator)enum.nextElement();
                             break;
                        catch(Exception ee){}
                   if(jhtoc != null)
                        JTree aTree = getNavTree(jhtoc);
                        aTree.setCellRenderer(new HelpTreeRenderer());
                        aTree.updateUI();
                        jhelp.updateUI();
              catch (Exception e)
                   System.out.println("Help Exception " + e.getMessage());
    class HelpTreeRenderer extends DefaultTreeCellRenderer{
         public Component getTreeCellRendererComponent(JTree tree, Object value,
              boolean selected, boolean expanded, boolean leaf, int row,
              boolean hasFocus) {
              try
                   DefaultTreeCellRenderer treeCellRender = (DefaultTreeCellRenderer)
                   super.getTreeCellRendererComponent(tree, value, selected, expanded,
              leaf, row, hasFocus);
                   DefaultMutableTreeNode node =(DefaultMutableTreeNode)value;
                   if(node.getLevel() == 1) treeCellRender.setIcon(getImageDepartment());
              catch (Exception e)
                   System.out.println("HelpTreeRenderer Inner Class WIP Viewer Exception " + e.getMessage());
              return this;
    }

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

  • Moving multiple files leaves icon on screen.

    I've been experiencing this bug wherein I select multiple files and drag and drop them onto an external drive. The copy completes just fine, but the 'image' of the grouped icons remains frozen on my screen, even across spaces. The only way to clear this ghost image is to restart finder. Is this a known bug? I've searched the forum and was unable to come upon anyone with a similar issue.

    On the Mac, you would press Command A (or  A) to
    select all.
    But, the problem you describe sounds like you are not
    clicking and holding when you go to move the files.
    If you click and then release, then yes only the file
    you are over will be selected.
    You need to position your mouse where you want it,
    then click and keep holding the button while you drag
    it to where you want them.
    AH, there's my mistake - yes, I had pressed Control-A and individually selected the various files I wanted to move (Cmd-A selects all which I did not want to do) but then I continued to hold the Control-A while I clicked on it to move the files - I needed to release Control-A before clicking and moving!
    Thanks for your help and such a quick reply.
    Vernon

  • JTree image icons

    Is there a way to change the little icon next to the nodes to an image?
    By default the nodes all have little icons on the left that look like a piece of paper. I couldn't find anything in the docs on it.

    Use a custom Renderer.
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

Maybe you are looking for