Jtree change childs icons

Hi All,
im wondering if someone try that.
i have a tree that include a parent and child/s.
when i selected the father all the child's should be selected too.
i was trying :
public void valueChanged(TreeSelectionEvent arg0) {
                    // TODO Auto-generated method stub
                    DefaultMutableTreeNode node = DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                    String s2 = (String)node.getUserObject();
                    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                   renderer.setLeafIcon(SelIcon);
                   renderer.setOpenIcon(SelIcon);
                   renderer.setClosedIcon(SelIcon);
                  //CheckNodes(node,renderer);
                    renderer.setBackgroundNonSelectionColor(frameColor);
                    tree.setCellRenderer(renderer);
               }     my problem it is changed the entire tree, and i want to change specific nodes.
if someone can help ill appreciate it.
Gabi

First Thanks for your answer.
i was trying your suggestion also:
public class IconRenderer extends DefaultTreeCellRenderer {
     private static final long serialVersionUID = 1L;
     Icon SelectedIcon;
     Icon NotSelectedIcon;
    public IconRenderer(Icon SelIcon,Icon NoTSelIcon) {
         SelectedIcon = SelIcon;
         NotSelectedIcon = NoTSelIcon;
    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(SelectedIcon);
              this.setLeafIcon(SelectedIcon);
              //this.setClosedIcon(SelectedIcon);
              //this.setOpenIcon(SelectedIcon);
         return this;
}in leaf nodes it was working fine but my problem here was with the parents.
what i mean is :
//this.setClosedIcon(SelectedIcon);
//this.setOpenIcon(SelectedIcon);
it marked the entire tree.
thanks

Similar Messages

  • 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

  • How to change JTree's node icon manually?

    Hi, I'm currently making messenger application using awt and swing. I've searched in google and here(got this), but till now I haven't got solution.
    I want to change user's status icon in the buddy list if the user's status is changed(such like offline and online).
    But for now I want to try to change the icon directly by pressing a button first before thinking about listener for the status.
    I have this tree
         CustomCellRenderer rosterTreeRenderer = new CustomCellRenderer();
            DefaultMutableTreeNode rosterRoot = new DefaultMutableTreeNode("root");
            DefaultMutableTreeNode rosterGroup = null;
             rosterGroup = new DefaultMutableTreeNode("group 1");
             rosterRoot.add(rosterGroup);
             rosterGroup.add(new DefaultMutableTreeNode("abc"));
             rosterGroup.add(new DefaultMutableTreeNode("dce"));
             rosterGroup = new DefaultMutableTreeNode("group 2");
             rosterRoot.add(rosterGroup);
             rosterGroup.add(new DefaultMutableTreeNode("zzz"));
             rosterGroup.add(new DefaultMutableTreeNode("xxx"));
             rosterGroup.add(new DefaultMutableTreeNode("yyy"));
                rosterTree.setCellRenderer(rosterTreeRenderer);This is the cell renderer
    public class CustomCellRenderer extends DefaultTreeCellRenderer
         private static final long serialVersionUID = 1L;
         public CustomCellRenderer(){
            public Component getTreeCellRendererComponent( JTree tree, Object value,
                    boolean isSelected, boolean expanded, boolean leaf, int row,
                    boolean hasFocus )
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              String     labelText = (String)node.getUserObject();
              if (isSelected)
                   System.out.println("selected");
                   this.setIcon(UIManager.getIcon("Tree.openIcon"));
                   //((DefaultTreeModel) tree.getModel()).nodeChanged(node);
            else if (leaf) {
                this.setIcon(UIManager.getIcon("Tree.leafIcon"));
              } else if (expanded) {
                   this.setIcon(null);
              } else {
                   this.setIcon(null);
              setText(labelText);
              return this;
        public Color getBackgroundNonSelectionColor() {
            return(null);
        public Color getBackground() {
            return(null);
    }Whenever I click the user, the user's icon change, the first phase of my testing is working.
    But after that I'm confused, how can I change the icon when I click a button at the roster frame. How to invoke and send parameter to change icon of specified user? I already read DefaultTreeCellRenderer javadoc but still haven't found clue to what I wanted, most of the methods noted with "Overridden for performance reasons".
    I've already searched for several days for this problem.. Hope someone can help me..
    Thanks

    Sorry I don't know how to delete my question from other forum. I also don't know about crossposting rule(I don't go into javaranch).
    I'm learning java by google and I'm really confused now, everyone I asked in real life doesn't know the solution. I'm doing a thesis making chat messenger, my lecturer also doesn't know how to solve my problem.
    Sorry I really don't know about the crosspoting rule. I only read the rule from each forum.
    Can someone help me please? :(

  • How do i change the icons back?

    I just downloaded iOS7 and immediately hate the icons and the text message look.  It looks like something a 10 year old girl would design.  Is there any way to change the icons and the text message look back to the way it looked in iOS6?  Or to at least use a different "skin" for text messages?
    I want a small computer not a child's toy.

    Someone said "writing here doesn't achive much"
    I disagree. Using the Apple feedback page will achieve less. That is a black hole where your comments get read by who knows. Out here in the open, on the internet, that's where things can happen!
    I've tried to get used to the new look iOS7 design, but I really hate it and prefer the old look for serious reasons.
    This isn't subjective opinion, there's a solid reason why the flat, bright simple interface is harder to use. Things are not visually segmented anymore. There's too much bleeding of one group of functions, or item, into other neighboring groups of interface elements. Whether it's selecting a menu item, tapping an icon, or a tab, the similarity of one element with the next, makes it harder to use because I'm constantly double checking what I'm about to tap because it's not intuitive. The old iOS6 interface was a more confident, visually helpful interface.
    The app store is like looking at wireframes from phase 1 of a new website build. Maybe Apple just couldn't be bothered taking it beyond wireframes. Those iOS7 designers went to the snow early I'm guessing, and left a bright white glaring screen which really is unpleasant to browse at night.

  • JTree change after Dnd

    Hello,
    I try to change the icon of the node source after a drag and drop in a JTree. Even if the icon information has changed in the node, I couldn't force the tree to reload with the changes.
    How could I do that ? Tell the treeCellRenderer to focus on the node source ?
    Regards,
    Anne

    You can use one of the methods of DefaultTreeModel
    ((DefaultTreeModel)tree.getModel()).nodeChanged(...)):
    void nodeChanged(TreeNode node)
              "Invoke this method after you've changed how node is to be represented in the tree. "
    void nodesChanged(TreeNode node, int[] childIndices)
              "Invoke this method after you've changed how the children identified by childIndicies are to be represented in the tree. "
    void nodeStructureChanged(TreeNode node)
              "Invoke this method if you've totally changed the children of node and its childrens children... "
    void nodesWereInserted(TreeNode node, int[] childIndices)
              "Invoke this method after you've inserted some TreeNodes into node. "
    void nodesWereRemoved(TreeNode node, int[] childIndices, Object[] removedChildren)
              "Invoke this method after you've removed some TreeNodes from node."
    Denis                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Change NativeWindow Icon

    Is it programmatically possible to change the icon of a window?  Specifically, a window created with HTMLLoader.createRootWindow.
    I know that I can change the Icon used for the entire application (NativeApplication.nativeApplication.icon)...  However, I would like to do it for a "child" HTML window.  Unfortunately, custom chrome is not an option because Transparency and the HTMLLoader don't play well together.
    Thanks in advance.

    You cannot do that -- sorry.

  • JTree's handle icon

    Hi,
    Can we change the icon of the handles of a JTree?
    If yes, how can we do that?
    Thanks,
    Jason

    It happens that when I click on the handle icon of the ancestor node, an Exception occurs:
    java.lang.NullPointerException
    What is goin' on?
    Here is code snippet:
    void jTree1_valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
    Object birac = node.getUserObject();
    TreePath niz = (TreePath)jTree1.getLeadSelectionPath();
    jTextArea1.setText("");
    if (jTree1.isVisible(niz)) {
    if (node.isLeaf()) {
    My_Class bt = (My_Class)birac;
    String tabela1 = bt.getImeTabele();
    if (qds1.isOpen()) {
    try {
    qds1.close();
    } catch (Exception ex){} } //if

  • Is there a way to change the icon associated with icloud account?

    Is there a way to change the icon associated with my iCloud account? It's currently a rose and i do not like it.

    Welcome to the Apple Support Communities
    Are you referring to your iCloud account picture or your user picture?
    It looks like you are referring to your user picture. To change it, open System Preferences > Users & Groups, press the picture box and choose the user picture you want from the ones that came by default. If you want to select a different picture stored on your Mac, drag that photo onto the picture box.
    If you want to change your iCloud account picture, open http://www.icloud.com and log in with your Apple ID. Then, press your name at the top right of the site and press the user picture. If you put the cursor on the picture box, you will see a button at the top of the box to change your picture

  • How I change the icon for iTunes songs?

    When I drag iTunes songs onto my desktop the icon is white with a gray iTunes icon. How can change this icon for all of my iTunes songs?

    Thanks Patrick. I used Control-Click on the actual audio file on my desktop opened the Show View Options menu and turned off the icon preview option. That changed my icons from gray with a white background to red with a white background which is exactly what I wanted.  You pointed me in the right direction. Appreciate it.

  • Change .pdf icons to generic icon instead of preview image

    How can I change the icon of a .pdf on the desktop to the more generic red and white Adobe logo instead of the little preview picture? With the old-style icon it's easy to determine what's a .pdf - with everything a little preview now (which is too small to tell anything, at least for me) I have to actually read the file name to see what type of file it is.
    Not the end of the world but it would be nice to change.
    thanks

    What app do you want your PDF files to open with when they are double-clicked?
    If you click on the Desktop, type Command-J, and in the Desktop's view-options window uncheck the box for "Show icon preview," you will convert all the Desktop icons to whatever image the default "Open with" app has provided. If you have set Adobe Reader as the default app for PDF files, the icon will look like this:
    !http://i55.tinypic.com/2r4hf6p.jpg!
    If you have set Preview as the default app, the icon will look like this:
    !http://i51.tinypic.com/264noea.jpg!
    I don't know of an automatic way to have PDF files display an Adobe icon and still have them open in Preview when double-clicked.

  • When I click on a link in an RSS feed it used to indicate that I'd viewed that particular link by changing the icon to the left of the link. It doesn't do that anymore. [SOLVED]

    When I click on a link in an RSS feed it used to indicate that I'd viewed that particular link by changing the icon to the left of the link. It doesn't do that anymore. This started happening right around the time I updated to Firefox 4, but may have been a little before that too. For some things, like news and web comics it's just a little annoying. For important things like looking for new journal articles for my job, it literally makes my job more difficult. So fixing this would make my day.

    I seem to have solved my own problem. When I disabled the add-on "Tab Renamizer" everything started working fine.

  • Change Dock Icons on OS 10.8.5

    Hi Mac Community!
    For all of us Mac lovers, the one thing we are fascinated with is the fact that Mac in notorious for giving the end user the power to personalize the computer's look and feel, as well as making commands extremely user friendly.
    This is not what I get from the last update to OS 10.8.5
    I want to change the icons on my dock, as I should being that I am the owner of a fairly expensive piece of equipment, but this seems impossible to do for the Finder icon. Is there any way this can be done without causing any problems in the system?
    Any ideas are appreciated! THANKS!

    You want to change the Finder icon or you want to remove the Finder icon from the dock. You weren't clear on that point

  • How to change the icon for print dialog?

    Hello,
    I have a JTable, and with the print() method, I'm able to bring up the Print dialog and successfully print the contents of the table. Example:
    myTable.print( JTable.PrintMode.FIT_WIDTH, myHeaderFormat, myFooterFormat );This works great, but one small detail I'd like to change is the icon in the top-left corner of the dialog. The icon is currently the default Java coffee cup icon, while the rest of my application uses my custom icon. I couldn't find any documentation in the API or tutorials that Java has listed which shows how to change the icon, so I'm not even sure if it's possible (but why shouldn't it be?).
    My question is this: Is it possible to change the default icon in the print dialog? Or do I have to either make my own print dialog somehow, or use a third-party print dialog?
    Thanks

    tjacobs01: Appreciate the assistance (despite your sass). I've already searched the API, tutorials, and this forum. I'm already well aware of the setIconImage() method for JFrame -- after all, that's how I set the icon for my other frames as I previously mentioned. However, I want to set the icon for the print dialog called from the print() method of JTable.
    How would I use setIconImage() for the print() method of JTable? The print() method returns a boolean value, not a JFrame, so I'm just not sure how to implement what you're saying.
    Thanks

  • How to change the icon of coffee on the titile bar

    Hi!
    I am having this problem that
    how to change the icon of coffee on the titile bar
    if someone know how please respond
    Asif

    Next time please post your question in the appropriate forum, since this forum discusses the Java3D API.
    The answer is use the Frame.setIconImage method.

  • How to change the icon for 'windows group' in Java 1.6 [Windows XP] ?

    Hello,
    I was wondering if there is a possibility to change the icon for 'windows group' in Java 1.6...
    I'm using Windows XP SP2. Now the windows from my Java 1.6 application are grouped with the standard Sun icon [screen below] on the group.
    http://img382.imageshack.us/img382/8995/iconbl1.png
    I would like to change the icon for my own. Is there a way to do that ?
    Please help.

    Whichever icon I use for the main frame (I tried few), after grouping the main frame and other sub-frames the icon is changed to standard 'Java Sun' icon as you can see in the screenshot from my first post. The problem occurs only when frames are grouped, when the are separated in the task bar their titles and icons are ok...
    So how can I change the icon/title for the group only (for Java 1.6 in Windows XP) ?

Maybe you are looking for

  • Snapshot status from within a VM

    Looking for a way to check if there are any snapshots currently on VM I am running in.  ESXi 5.5, Guest OS is RHEL6.  I can look at things like cpu and memory limits and reservations, plus host swap and balloon driver status all from toolbox command,

  • Audio Queue Help

    Hi! Using sample code as a base, I've been able to get .wav and .mp3 files playing on the iPhone I'm using a simple AudioQueueCallback that uses AudioFileReadPackets to read audio packets and add them to the AudioQueue buffer using AudioQueueEnqueueB

  • Select...Model query giving error when compiled in form6i's WVI trigger

    friends i have this installed at my home; Forms [32 Bit] Version 6.0.8.25.2 (Production) Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production and i have a query which is running fine at the back-end, select avgprice from ( select t.

  • Nokia 2330 contacts.

    Hey there, I wondering if anyone can help. I have a Nokia 2330 but the screen recently broke. All I can see now is roughly the top third of the screen. Obviously I need a new phone but unfortunately my contacts are saved to the phone, not the sim. Co

  • Selecting even rows

    Hi everybody, Whats wrong with the simple query: SQL> select * from unxtb002 where mod(rownum, 2)=0; It returns no rows. I intend to select even rows from the table. Regards Mona