4

I've seen plenty of examples for changing the icon of nodes during tree instantiation, but I'd like a way to dynamically change the icon of an individual node later. So, in my main code I add my custom renderer to my tree:

// Icon I want to set nodes to later
ImageIcon checkIcon = new ImageIcon("check.jpg");

// Creates tree with my nodes
JTree tree = new JTree(nodes.top);

// Create custom renderer
Scenario1Renderer renderer = new Scenario1Renderer();

// Set to single tree selection 
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

// Set tree to my custom renderer
//renderer.setRendererIcon(greenIcon);
tree.setCellRenderer(renderer);

My code in the renderer is

public class Scenario1Renderer extends DefaultTreeCellRenderer {

ImageIcon rendererIcon;

    public void setRendererIcon(ImageIcon myIcon){
      this.rendererIcon = myIcon;
    };

public Component getTreeCellRendererComponent( 
         JTree tree, 
         Object value, 
         boolean sel, 
         boolean expanded, 
         boolean leaf, 
         int row, 
         boolean hasFocus)
{ 

    Component ret = super.getTreeCellRendererComponent(tree, value,
            selected, expanded, leaf, row, hasFocus);
            //setIcon( rendererIcon ) ;
            return ret;
    } 

So, obviously if I set my rendererIcon, it'll paint all my nodes with the icon I pass in during tree instantiation. I instead want some sort of method that can set the icon of an individual node later on in the execution of my program.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Matt
  • 295
  • 3
  • 6
  • 17
  • there I can't see any difference, don't understand, whats reason – mKorbel Feb 19 '13 at 22:18
  • *"I've seen plenty of examples for changing the icon of nodes during tree instantiation, but I'd like a way to dynamically change the icon of an individual node later"* So add that ability to the renderer. I don't see how this is special in any way. I am surprised your research has not shown up examples of a 'dynamic' way to render the cells. There should be a great number of e.g.s that show how to render the data differently at run-time and depending on the content. – Andrew Thompson Feb 20 '13 at 01:09

1 Answers1

8

You can have different icons that you can set according to different conditions. Below is a simple example that changes icon of a selected node:

import java.awt.Component;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;

public class TestTree {
    private static void createAndShowUI() {
        JFrame frame = new JFrame();
        final JTree tree = new JTree(buildDemoModel());

        tree.setCellRenderer(new DefaultTreeCellRenderer() {
            private Icon loadIcon = UIManager.getIcon("OptionPane.errorIcon");
            private Icon saveIcon = UIManager.getIcon("OptionPane.informationIcon");
            @Override
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value, boolean selected, boolean expanded,
                    boolean isLeaf, int row, boolean focused) {
                Component c = super.getTreeCellRendererComponent(tree, value,
                        selected, expanded, isLeaf, row, focused);
                if (selected)
                    setIcon(loadIcon);
                else
                    setIcon(saveIcon);
                return c;
            }
        });
        tree.setVisibleRowCount(10);
        frame.add(new JScrollPane(tree));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }

    private static DefaultTreeModel buildDemoModel() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        root.add(new DefaultMutableTreeNode("A"));
        root.add(new DefaultMutableTreeNode("B"));
        root.add(new DefaultMutableTreeNode("C"));

        return new DefaultTreeModel(root);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowUI();
            }
        });
    }
}
tenorsax
  • 21,123
  • 9
  • 60
  • 107
  • 4
    For reference, a similar approach is shown [here](http://stackoverflow.com/a/14097270/230513). – trashgod Feb 20 '13 at 02:20
  • Also note that `((DefaultMutableTreeNode) value).getUserObject()` yields an Object you can cast to the original item you placed into the tree. – kmort Mar 11 '16 at 16:03
  • for reference, `DefaultTreeCellRenderer` will change the node's selection background and foreground color ,when you click any node the node not show gray highlight , this issue you can use `this.selected = selected; this.hasFocus = hasFocus;` to fix it . Hope this helps others. – Alter Hu Oct 17 '16 at 06:32
  • Do you know if it is possible to target individual handles when the mouse is over them? See [here](http://stackoverflow.com/questions/40887102/add-rollover-to-jtree-handles) – Dan Nov 30 '16 at 21:21
  • 2
    @Dan I don't think TreeUI supports this out of the box. if it worth the trouble you'd have to extend TreeUI. Take a look at `BasicTreeUI.paintExpandControl()`. – tenorsax Dec 01 '16 at 23:09
  • 1
    @tenorsax Thank you. I will look into this – Dan Dec 01 '16 at 23:12
  • 1
    @tenorsax Thanks again. I now have a solution working off what you said. If you interested see [here](http://stackoverflow.com/a/40943405/4601149) – Dan Dec 03 '16 at 01:44