Defining different icons for TreeNode by extending DefaultTreeCellRenderer

Hello all,
I'm using a JTree to display project, folder and files. I'd like to have different icons for open project, close project, open folder, close folders, and files
but i got for the root which is a project object a folder icon and for folder when it is not expanded i got project icon and the when i expand it i got a folder icon, can someone help me please
Here is my code :
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
     private Icon openIcon = null;
     private Icon closeIcon = null;
     private Icon leafIcon = null;
     private Icon projectOpenIcon = new ImageIcon("icons/book_open.png");
     private Icon projectCloseIcon = new ImageIcon("icons/book_blue.png");
     private Icon folderOpenIcon = new ImageIcon("icons/folder.png");
     private Icon folderCloseIcon = new ImageIcon("icons/folder_closed.png");
     private Icon fileIcon = new ImageIcon("icons/document.png");
     @Override
     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);
          LogescoTreeNode node =
               (LogescoTreeNode)value;
          Object obj = node.getUserObject();
          System.out.println(obj.getClass().toString());
          if(openIcon == null) {
               openIcon = this.getOpenIcon();
               if(openIcon != null) {
                    if(obj instanceof LProject) {
                         openIcon = projectOpenIcon;
                         this.setOpenIcon(openIcon);
                         openIcon = null;
                    } else if(obj instanceof LFolder) {
                         openIcon = folderOpenIcon;
                         this.setOpenIcon(openIcon);     
                         openIcon = null;
          if(closeIcon == null) {
               closeIcon = this.getClosedIcon();
               if(closeIcon != null) {
                    if(obj instanceof LProject) {
                         closeIcon = projectCloseIcon;
                         this.setClosedIcon(closeIcon);
                         closeIcon = null;
                    } else if(obj instanceof LFolder) {
                         closeIcon = folderCloseIcon;
                         this.setClosedIcon(closeIcon);
                         closeIcon = null;
          this.setLeafIcon(fileIcon);
          return this;
}Thank you.

Hi all,
I changed my code a bit knowing that the renderer is global to the tree so my (openIcon == null) is called only once for the first node.
Here is my new code :
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
     private Icon projectOpenIcon = new ImageIcon("icons/book_open.png");
     private Icon projectCloseIcon = new ImageIcon("icons/book_blue.png");
     private Icon folderOpenIcon = new ImageIcon("icons/folder.png");
     private Icon folderCloseIcon = new ImageIcon("icons/folder_closed.png");
     private Icon fileIcon = new ImageIcon("icons/document.png");
     @Override
     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);
          LogescoTreeNode node =
               (LogescoTreeNode)value;
          Object obj = node.getUserObject();
          System.out.println(obj.getClass().toString());
          if(obj instanceof LProject) {
               this.setIcon(expanded ? projectOpenIcon : projectCloseIcon);
          } else if(obj instanceof LFolder) {
               this.setIcon(expanded ? folderOpenIcon : folderCloseIcon);
          } else {
               this.setIcon(fileIcon);
          return this;
     }

Similar Messages

  • I want to change different icon for different leaf node

    Hi,
    i am reading file system(win 2000)and showing in a tree.i want to
    show different icon for different file extension.
    Pl suggest me with sample code,how should i do?
    Thanx

    Hi...
    To do this, u need to write ur own TreeCellRenderer.
    ex :
    class FileSystemTreeCellRenderer extends JLabel implements TreeCellRenderer
         File file= null;
         public FileSystemTreeCellRenderer(File f)
              this.file = f;
         public Component getTreeCellRendererComponent
                   JTree tree,
                   Object value,
                   boolean selected,
                   boolean expanded,
                   boolean leaf,
                   int row,
                   boolean hasFocus
              if(file.isDirectory())
                   setIcon("your image");
                   setText("file/dir name");
              else
                   setIcon("your other image");
                   setText("file/dir name");
         return this;
    Hope it suits ur need .. (also, using the file extensions, u can set different icons following the above strategy...)
    Regards,
    Ramanujam

  • How to display different icon, for different node of jtree

    Hi All,
    How to display different icon, for different node of jtree

    you haven't responded to my last post here: [http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676|http://forums.sun.com/thread.jspa?threadID=5323190&messageID=10382676#10382676]

  • How to set different Icons for Jtreenode

    How to set different Icons for Jtreenode,i want to set icons for jtreenode,not only for leaf,open,closeicon,i hope that each node has a different icon.Thanks!

    you need to check for the node value within a renderer, then assign an icon based on what you expect to get back.
    check out this page. http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • How to set different icons for different windows which is seen in the top left corner?

    Hi
    How to set different icons for different windows which is seen in the top left corner? I know when building exe there is a option to edit icons or add icons and that icon is default for all the windows in the project. But i want different icons for different windows which is possible in VB.
    Is there any way to set icon by calling any dlls.
    Thanks & Regards
    Samuel J
    [email protected]

    Hi Sam,
    no problem. See the attachment.
    Mike
    Attachments:
    TestIcon_LV85.zip ‏44 KB

  • Different icons for each TreeNode...?

    Is it possible to make each (or at least some) of the TreeNode's in a JTree display different icons?
    H

    Yes, you can use a TreeCellRenderer to control how nodes are displayed. Look around there are several good examples available.
    Cheers
    DB

  • Ho to set different Icon for different Jtree Nodes dynamically??

    Dar Friends:
    I have following code.
    But if poosible I hope to:
    [1]. Dynamically assign or st each node with different Icons;
    [2]. these icons have different sizes, hope to resize them with same size, ie. 20X 20
    But try whole day, no idea how to to it,
    Can somebody throw a light??
    Thanks
    Good weekends
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    /** JTree with missing or custom icons at the tree nodes.
    *  1999 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    public class CustomIcons extends JFrame {
      public static void main(String[] args) {
        new CustomIcons();
      private Icon customOpenIcon = new ImageIcon("images/Circle_1.gif");
      private Icon customClosedIcon = new ImageIcon("images/Circle_2.gif");
      private Icon customLeafIcon = new ImageIcon("images/Circle_3.gif");
      public CustomIcons() {
        super("JTree Selections");
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode child;
        DefaultMutableTreeNode grandChild;
        for(int childIndex=1; childIndex<4; childIndex++) {
          child = new DefaultMutableTreeNode("Child " + childIndex);
          root.add(child);
          for(int grandChildIndex=1; grandChildIndex<4; grandChildIndex++) {
            grandChild =
              new DefaultMutableTreeNode("Grandchild " + childIndex +
                                         "." + grandChildIndex);
            child.add(grandChild);
        JTree tree3 = new JTree(root);
        tree3.expandRow(3); // Expand children to illustrate leaf icons
        DefaultTreeCellRenderer renderer3 = new DefaultTreeCellRenderer();
        renderer3.setOpenIcon(customOpenIcon);
        renderer3.setClosedIcon(customClosedIcon);
        renderer3.setLeafIcon(customLeafIcon);
        tree3.setCellRenderer(renderer3);
        JScrollPane pane3 = new JScrollPane(tree3);
        pane3.setBorder(BorderFactory.createTitledBorder("Custom Icons"));
        content.add(pane3);
        pack();
        setVisible(true);
    }

    Thanks for your advice,I post my code as below, (I cannot post Max 5000, so post twice)
    [1]. main:
    import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    import java.awt.*;
         public class JTreeNew  extends JFrame {
           public JTreeNew() {
             super("Editable Tree Frame");
                JTreeSub js = new JTreeSub();
             setSize(200, 200);
            // WindowUtilities.setNativeLookAndFeel();
            // addWindowListener(new ExitListener());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
           public class JTreeSub  extends JTree implements TreeSelectionListener{
                DefaultTreeModel treeModel;
                JTree tree;
                ContainerIconNode selectedNode;
                public JTreeSub() {
                super();
                init();
                public void init(){
                  ContainerIconNode Root = new ContainerIconNode("images/Root.GIF");
                  ContainerIconNode Animal = new ContainerIconNode("images/Animal.GIF");
                  ContainerIconNode Cat = new ContainerIconNode("images/Cat.GIF");
                  ContainerIconNode Fish = new ContainerIconNode("images/Fish.GIF");
                  ContainerIconNode GoldFish = new ContainerIconNode("images/GoldFish.GIF");
                  ContainerIconNode CatFish = new ContainerIconNode("images/CatFish.jpg");
                  ContainerIconNode Solomon = new ContainerIconNode("images/Solomon.GIF");
                  ContainerIconNode DogFish = new ContainerIconNode("images/DogFish.GIF");
                  ContainerIconNode Dog = new ContainerIconNode("images/Dog.jpg");
                  ContainerIconNode Mouse = new ContainerIconNode("images/Mouse.GIF");
                  ContainerIconNode Chicken = new ContainerIconNode("images/Chicken.GIF");
                  ContainerIconNode Pig = new ContainerIconNode("images/Pig.GIF");
                  treeModel = new DefaultTreeModel(Animal);
                  tree = new JTree(treeModel);
                  tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                  ToolTipManager.sharedInstance().registerComponent(tree);
                  //Listen for when the selection changes.
                 tree.addTreeSelectionListener(this);
                  tree.setEditable(true);
                  treeModel.insertNodeInto(Animal,Root, 0);
                  Animal.add(Cat);
                  Animal.add(Fish);
                  Fish.add(GoldFish);
                  Fish.add(CatFish);
                  Fish.add(Solomon);
                  Fish.add(DogFish);
                  Animal.add(Dog);
                  Animal.add(Mouse);
                  Animal.add(Chicken);
                  Animal.add(Pig);
                  tree.expandRow(3); // Expand children to illustrate leaf icons
         //         DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
         //         renderer.setOpenIcon(Animal.getImageIcon());
         //         renderer.setClosedIcon(Dog.getImageIcon());
         //         renderer.setLeafIcon(CatFish.getImageIcon());
         //         tree.setCellRenderer(renderer);
                  ImageIcon startIcon = new ImageIcon("images/89.gif");
                  tree.setCellRenderer(new MyRenderer(startIcon));
                  getContentPane().add(tree, BorderLayout.CENTER);
              @Override
              public void valueChanged(TreeSelectionEvent e) {
                   selectedNode = (ContainerIconNode)
                                    tree.getLastSelectedPathComponent();
                 if (selectedNode == null) return;
                 Object nodeInfo = selectedNode.getUserObject();
                 if (selectedNode.isLeaf()) {
                      System.out.println("<JTreeNew> Node is  leaf=");
                 } else {
                      System.out.println("<JTreeNew> Node is  folder");
           private class MyRenderer extends DefaultTreeCellRenderer {
                 Icon nodeIcon;
                 public MyRenderer(ImageIcon icon) {
                      nodeIcon=icon;
                 public Component getTreeCellRendererComponent(
                                     JTree tree,
                                     Object value,
                                     boolean sel,
                                     boolean expanded,
                                     boolean leaf,
                                     int row,
                                     boolean hasFocus) {
    //                  System.out.println("<JTreeNew> Tree="+ tree);
    //                  System.out.println("<JTreeNew> nodeIcon="+ nodeIcon);
                      System.out.println("\n<JTreeNew> value="+ value);
                      System.out.println("<JTreeNew> sel="+ sel+"\n");
    //                  System.out.println("<JTreeNew> expanded="+ expanded);
    //                  System.out.println("<JTreeNew> leaf="+ leaf);
    //                  System.out.println("<JTreeNew> row="+ row);
    //                  System.out.println("<JTreeNew> hasFocus="+ hasFocus);
                     return this;
           public static void main(String args[]) {
                JTreeNew st = new JTreeNew();
                st.setVisible(true);
         }

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

  • Jtable: set different icons for  selection/deselection

    Hai,
    I have designed a Jtable, I would like to set a column that has to show different icons when selected/deselected that row. To be specific when you click for the first time, it has to show ICON1 and if you click again it has to show ICON2. Any ideas ???
    Thanks,
    Bala.

    I haven't tried this - so take it with a grain of salt. In your table model, you can define the getColumnClass for the column as ImageIcon.class. In the getValue for that column, you would return the icon.
    In order to get the cell to act like a button .. so you can alternate between the icons ... is a little more complex. There is a book on Advanced Swing by Kim Topley that gets into making cells act like buttons. This part works because I have tried it -- but I wasn't displaying icons.
    good luck!

  • How to set different icon for different type of document

    Hi,
    In my repository, we have different kinds of document (crystal report, word document, excel, jpg ...) and we wanna show specific icon for each kind. In my used ResourceRender I cann't see where to change (rnd:icon?)
    Could someone tell me how to achieve that? Thanks
    Ray

    Hi Ray Li,
    in KM icons are mapped to mime types. You can add a mapping or change an existing one as follows:
    1. Go to Systemadministrarion - System Configuration - Knowledge Management - Content Management - Utilities - Icons
    2. Add your mime mapping or change an existing one. To determine the correct mime type of your documents, just have a look at the details dialog in KM.
    3. The path to the icons points (by default) to following directory on your KM server: usr\sap\SID\SYS\global\config\cm\etc\public\mimes\images
    Here you can replace images or add some new.
    Hope this helps,
    Carsten
    Seems like somebody thought the same thought bit faster than I did. Would like to delete my answer that does not contain any additional info. But dunno how to.
    Message was edited by: Carsten Buechert

  • Different icon for Frame's title bar and alt tab

    I have been using Frame.setIconImage to supply the image icon for the title bar and (on Windows, the <alt><tab> image). The trouble is there is only one image for both but one is usually small 16x16 and the other is usually large 32x32. What I have been doing is creating an image that is 32x32 but scales back to 16x16 and still looks good.
    The trouble is it is tricky to create graphics like that. I wondered is there a way to specify one image for the title bar and another image for the <alt><tab> image?
    thanks,
    Ian

    Has anyone encountered this problem before? Is there
    a solution? Or can anyone say definitivly that
    specifying the title bar icon and the <alt><tab> icon
    separately is not possible?Sorry- you can't do it. Windows apps can do this easily because they use a .ico that can contain both the 16x16 and 32x32.
    There are a couple of hacks I tried once, trying to swap icons based on events, but they are horrible hacks and don't work well enough to use. Your choices are as follows:
    1. Use a 16x16 .gif as your icon and have it look good in the upper left hand corner of your frame but horrible during alt-tab,
    or
    2. Use a 32x32 .gif and have it look poorly in the upper left hand corner of your frame but good during most other times.
    I'd choose #1.
    (The reason behind all of this is Java does a much worse job of resizing your icon than you could do yourself with a little work in Paint Shop Pro.)

  • Different icon for a different user.

    How can one user change the icon for an applicatin to his or her preference, but NOT change it for other users on the same computer? Am I correct in assuming that, since applications are shared between user, that it must have the same icon for everyone? Ex: Can John have a green apple for iPhoto while Jane as a yellow balloon? Thanks much for any help.

    Hey Troy,
    Well, yes this can be done. The trick is to use aliases. Let's say that iPhoto is the app you want to "modify." OK, drag it out of your Dock. Now, navigate to the iPhoto application and control-click (or right-click) on it and choose "Make Alias" from the contextual menu.
    Drag that new alias out of the Applications folder to your Desktop (or some other location in your HOME folder). Name it how you like, then click on it and press Apple-I to open a Getinfo window. Do the same for some other icon that you want to use for your iPhoto "app."
    In the Getinfo windows, click on the icon preview for the icon you want to use, and press Apple-C to copy it. Go to the window for your little "app" select its icon preview, and press Apple-V to paste over it.
    Finally, drag your alias into the Dock, replacing the real iPhoto application that you dragged out earlier.
    Scott

  • Why does iOS7 and Mavericks have different icons for apps?

    I love apple simple desige and intuitive approach.
    BUT why does not Contacts, Calender etc have the same icons anymore between your operating systems?
    This is not simple and it is not intuiative.....
    Alexander

    The removal of all the skeuomorphic elements from iOS and OS X is only partially complete. Doubtless we'll see this change as updates come out, though whether Apple will go with the exact same icons in both iOS and OS X for any given app remains to be seen. You can express your opinion to Apple via their feedback page, if you wish:
    http://www.apple.com/feedback/macosx.html
    Regards.

  • Different Icon in a JTree

    Helle mates,
    is it possible to display different icons in a JTree?
    At present, I have the same folder-icons for all folders and the same leaf-icons for each leaf but I want different pics for each folder and for each folder different leaf-icons.
    Is that possible?
    I searched for it but nothing could help me so far. Hopefully, someone got an idea in here.
    Thank you so much

    you need a TreeCellRenderer. it will allow you to draw different icons for different nodes. for example like so:
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Model model = (Model)((DefaultMutableTreeNode)value).getUserObject();
        setBackgroundNonSelectionColor(model.conditionColor());
        setBackgroundSelectionColor(model.conditionColor().darker());
        setOpenIcon(model.icon());
        setLeafIcon(model.icon());
        setClosedIcon(model.icon());
        Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
        if (selected) setForeground(Color.white);
        return c;
    aJTree.setCellRenderer(new MyTreeCellRenderer());
    :thomas

  • Can Tree's folder icon node changed to different icon?

    Hi,
    Currently, the tree and tree table node's icon is a "folder" icon. Can this be customized to different icons? We would like to have different icons for the nodes for different level in the tree/tree table. For example, level 1's node is icon A; level 2's node is icon B, etc...
    Any suggestions?
    Thanks.
    -Mina

    Hi,
    I think the right way of doingthis indeed is skinning. I would try to
    - set a styleClass value to the styleClass property using EL against a managed bean method.
    - The managed bean method now is called for each node. Use EL in the managed bea method to access the #{node} EL to determine the row you are on
    - set the style class to e.g. level1, level2, level3
    - Then in the skinning you use
    level1 af|tree...{}
    level2 af|tree...{}
    To define the different icons for the tree levels. Note that using DAF all icons are using folders. So there is no sense in skinning leaf icons
    Frank

Maybe you are looking for