JTree:TreeCellRenderer未按预期执行

时间:2021-02-08 12:36:42

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?

但是,这会使我树中的所有节点都变粗。怎么了?

2 个解决方案

#1


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

如果级别不是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

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

#2


In your code you set font bold for level 1 but what about the other levels. Where is the else condition? Can you please try this?

在您的代码中,您为级别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;
}
}

#1


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

如果级别不是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

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

#2


In your code you set font bold for level 1 but what about the other levels. Where is the else condition? Can you please try this?

在您的代码中,您为级别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;
}
}