javaswingfontsjtreetreecellrenderer

JTree: TreeCellRenderer not doing as expected


In a nutshell, I want the tree be rendered such that the first level is bold.

public class TreeRenderer1 extends DefaultTreeCellRenderer {

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
        boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
    super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);

    DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;

    if (node.getLevel()==1) {
        setFont(getFont().deriveFont(Font.BOLD));
    }

    return this;
}
}

This, however, make all the nodes in my tree bold. What is wrong?


Solution

  • Reset the font state of the render if the level is NOT 1...

    if (node.getLevel()==1) {
        setFont(getFont().deriveFont(Font.BOLD));
    } else {
        setFont(getFont().deriveFont(Font.PLAIN));
    }
    

    Render's are a shared resource, any changes you make to it are carried onto the next element to be rendered, so you must always make sure you set it to a "default" state at some point