我正在使用自定义TreeCellRenderer来自定义树的颜色。 如果某些条件成立,我想给父节点和子节点着色。 这是我的代码:
public class MyTreeCellRenderer 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);
// My tree is made of strings only
String node = (String) ((DefaultMutableTreeNode) value).getUserObject();
if (leaf) {
// Paint the leaf in blue
setForeground(new Color(0,0,255));
// Here I got: java.lang.NullPointerException
String parent = (String) ((DefaultMutableTreeNode) value).getParent().toString();
}
如您所见,当我尝试检索父项时,自从我收到NullPointerException以来,出现了一些问题。这对我来说听起来很奇怪,因为它是一个叶节点。
我做错了什么?