JTree:TreeCellRenderer 未按预期执行

JTree: TreeCellRenderer not doing as expected

简而言之,我希望树的第一层是粗体。

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

然而,这使我的树中的所有节点都变成了粗体。怎么了?

如果级别不是 1...

,则重置渲染的字体状态
if (node.getLevel()==1) {
    setFont(getFont().deriveFont(Font.BOLD));
} else {
    setFont(getFont().deriveFont(Font.PLAIN));
}

渲染器是共享资源,您对其所做的任何更改都会传递到下一个要渲染的元素,因此您必须始终确保在某个时刻将其设置为 "default" 状态

在您的代码中,您为级别 1 设置了粗体,但其他级别呢? else条件在哪里?你能试试这个吗?

@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));
    } else {
        setFont(getFont().deriveFont(Font.PLAIN));
    }

    return this;
}
}