How to change background color of a jtree node

57 Views Asked by At

I am having a netbeans project with jtree and DefaultMutableTreeNode. I have to search a node in the tree by its name and want to highlight it, for highlighting I think I will change the background color of the node.

For searching the node I made a func, `

public DefaultMutableTreeNode searchNode(DefaultMutableTreeNode treeRoot, String nodeStr) {
        DefaultMutableTreeNode node = null;
        Enumeration e = treeRoot.breadthFirstEnumeration();
        while (e.hasMoreElements()) {
          node = (DefaultMutableTreeNode) e.nextElement();
          if (nodeStr.equals(node.getUserObject().toString())) {
            return node;
          }
        }
        return null;
    }

now I can search a desired node by its name,DefaultMutableTreeNode searched = searchNode(root, "mynode");`

it gives me the node but now I am stuck how to highlight the searched node returned by this function, I need to make something like, searched.changeBackgroundColor(Color.RED); to highlight the searched node.

Please help me to do it. Thanks

1

There are 1 best solutions below

1
Rob Spoor On

The model, in this case DefaultMutableTreeNode, doesn't do its own rendering. It's just for storing data.

All rendering is done through implementations of TreeCellRenderer. There is one provided implementation, DefaultTreeCellRenderer.

The best way to go forward is to create a sub class of DefaultTreeCellRenderer, and override its getTreeCellRendererComponent method. For example:

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

    Component component = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    if (value == searched) {
        component.setBackground(Color.RED);
    }
    return component;
}