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

Similar Messages

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

  • Displaying nodes in a JTree with different icons

    Please can you help me? I have set up a JTree that handles different icons for each item in the tree. The items are all independent and there is no way of grouping them together, so to get around the problem of displaying them in the tree I have stored them in array of images, such that each row in the tree maps to the correct element of the tree (or so I thought).
    However, my overridden version of getTreeCellRendererComponent() displays interesting behaviour. If one of the branches in tree is collapsed, then the number of rows displayed in the tree differs from when it is expanded. This renders my use of an array useless because it doesn't map to what I thought was the structure of the tree and my icons do not align to the correct textual information.
    How can I map my images to the tree so that it displays correctly when the branches are expanded or collapsed?

    You need to be able to figure out what icon to display based on the object that the tree cell is rendering. In other words, the object should have an attribute that you can query that tells your cell renderer what icon to use. If all else fails, change your object to contain a reference to the icon that should be displayed next to it.

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

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

  • 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

  • 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

  • When i put a cd into my itunes library sometimes it does not get stored under the same cover. sometimes stored under 3 or 4 different icons. what can i do to prevent this. how do i get all the songs back under the same kicon in one place? help would be a

    sometimes when i put a new cd into my itunes libray all the songs do not end up under the same icon. sometimes it will go into the library under 3 or 4 different icons (album artwork) and sometimes if there are for example 12 songs on the cd each song goes under a separate icon.this seams to happen more frequently with cd's that have different artists on one disc and not just one artist performing all the songs.
    is there anyway to prevent this from happening?
    is there a way to go into my library and get them put back under one icon as it should have been? i have tried drag and drop and it will not work.
    thanks to anyone that can offer some help

    The sort fields should generally be empty unless you've putting in custom values to sort solo artists by their surnames. You can apply common changes to thousands of tracks at once, just don't apply the wrong change because there is no undo.
    It is a good idea to backup before undertaking large scale changes. See this backup tip for a suggested approach.
    tt2
    Message was edited by: turingtest2

  • HT203421 I have recently purchased some apps from the app store and after downloading them, the icon that appears in the dock changes to a different icon. It is now the same icon appearing on all newly downloaded apps.  Does anyone know what is happening

    I have recently purchased some apps from the app store and after downloading them, the icon that appears in the dock changes to a different icon. It is now the same icon appearing on all newly downloaded apps.  Does anyone know what is happening here? Even updating an older game app resulted in the original game icon changing to the new identical icon that all new apps are appearing with.  This new icon is like a page with a ruler, pencil and paintbrush. Any tips on how to stop this or how to revert to the icon as it appears on the app store would be appreciated.

    https://discussions.apple.com/thread/6132949?tstart=0

  • How to display different icon within WDA alv table base on row data ?

    Hi,
    is that possible to display different icon for every row within ALV table depending on the row data ?
    for instance if the status 'S' display ~Icon/SuccessMessage and 'E' display ~Icon/ErrorMessage ?
    because base on this code below i only can set 1 icon for the whole row data.
    LOOP AT lt_columns ASSIGNING <fs_column>.
        CASE <fs_column>-id.
          WHEN 'ICO'.
            CREATE OBJECT lr_caption.
               lr_caption->set_image_source( value = '~Icon/SuccessMessage').
               <fs_column>-r_column->set_cell_editor( lr_caption ).
        ENDCASE.
      ENDLOOP.
    Thank you in advance.
    Fernand

    Hello,
    Yes it is possible to display different images based on data.
    For that what you can do is create one attribute 'STATUS' of type string in context node which you are mapping to ALV.
    And fill that attribute with the path to image based on your requirement like for status 'S' set the attribute to ~Icon/SuccessMessage and if status is 'E', set it to ~Icon/ErrorMessage at runtime.
    Now in the settings for ALV use the following code:
    * Display icon in column seatsocc
      DATA: lr_column TYPE REF TO cl_salv_wd_column,
            lr_image TYPE REF TO cl_salv_wd_uie_image,
            lv_icon TYPE string.
      lr_column = lv_model->if_salv_wd_column_settings~get_column( 'SEATSOCC' ).
      CREATE OBJECT lr_image.
      lr_image->SET_SOURCE_FIELDNAME( 'STATUS' ).
      lr_column->set_cell_editor( lr_image ).
    in the above code, column 'SEATSOCC' will be displayed as an icon.
    Sample code to fill the attribute 'STATUS'
    LOOP AT lt_flights INTO ls_flight.
        lv_seatsfree = ls_flight-seatsmax - ls_flight-seatsocc.
        IF lv_seatsfree = 0.
          ls_flight-status = 'ICON_RED_LIGHT'.
        ELSEIF lv_seatsfree <= 50.
          ls_flight-status = 'ICON_YELLOW_LIGHT'.
        ELSE.
          ls_flight-status = 'ICON_GREEN_LIGHT'.
        ENDIF.
        MODIFY lt_flights FROM ls_flight.
      ENDLOOP.
    Hope this helps!
    Regards,
    Srilatha
    Edited by: Srilatha M on Jun 25, 2010 12:02 PM

  • I have 3 different email account, I would like to see them in different icons, it`s that possible.

    I have 3 different email account, I would like to see them in different icons on the screen, it`s that possible.?

    No.

  • How do I get my 2 email accounts on different icons?

    How do I get my 2 email accounts on different icons? I already have my yahoo account & my work account set up. I just want to have different mail icons for them. Is this possible?
    Thanks

    You don't. You can view the individual accounts within the mail app if you want, or you can see them in the unified inbox.

  • 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

Maybe you are looking for

  • Opening a frame from an applet

    Hi, I want to open a frame in my applet. If I'm using swing, JApplet opening a JFrame, is it possible to keep the frame open if the user browses away from the page that holds the applet? Are there any tricks? I've tried opening it in a new Thread, bu

  • Can I use the ram...

    Hi, I was wondering if I can use the ram from a Macbook core 2 duo in a Macbook Pro. Is it the same? Thanks

  • Menu/Title page of DVD blurry

    I have a new MacBookPro and just tried to burn my first DVD in iDVD8. I used 7.0 Themes - Centerstage. When I playback the DVD, the text on the main menu/title page looks fuzzy. Not crisp like in iDVD. I checked the DVD on: '08 MacBookPro, 1440x900x3

  • Next_day is not giving correct date

    SELECT NEXT_DAY('01-apr-2013','monday') from dual; When i fire the above query it suppose to display '01-apr-2013' but it is displaying '08-apr-2013' which is wrong.. Pls suggest.

  • Problem with clocking (I think it is a hardware problem)

    I have an HP Pavilion dv5 1199ee, and using Win 7-64 bit. due to an accident the notebook was forced to be open widely (180 degrees). Since that incident, the clocking system is having problem retaining the right time, and the time displayed doesn't