简而言之,我希望树被渲染成第一级是粗体。
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;
}
}
然而,这会使我树中的所有节点都变粗。有什么问题?
答案 0 :(得分:3)
如果级别不是1
...
if (node.getLevel()==1) {
setFont(getFont().deriveFont(Font.BOLD));
} else {
setFont(getFont().deriveFont(Font.PLAIN));
}
渲染是共享资源,您对其进行的任何更改都会传输到要渲染的下一个元素,因此您必须始终确保在某个时刻将其设置为“默认”状态
答案 1 :(得分:2)
在您的代码中,您为级别1设置了字体粗体,但其他级别则是如此。其他条件在哪里?你能试试吗?
@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;
}
}