根据节点中存储的数据突出显示jtree中的特定节点 [英] Highlighting specific nodes in a jtree depending on data stored in the node
问题描述
我有一个显示jTree的应用程序.树中的每个节点都有一个名为flagged
的布尔字段,指示是否需要用户的注意.
I have an application that displays a jTree. Each node in the tree has a boolean field called flagged
which indicates whether it requires attention or not from the user.
如果该字段为true
,那么我希望将其突出显示为红色,否则不要突出显示.
If the field is true
, then I would like it to be highlighted in red, otherwise no highlighting.
什么是完成此任务的好方法?我应该扩展DefaultTreeCellRenderer
吗?实现我自己的自定义TreeCellRenderer
?还有其他方法吗?
What is a good way to accomplish this? Should I extend DefaultTreeCellRenderer
? Implement my own custom TreeCellRenderer
? Some other method?
推荐答案
由于您要进行的自定义渲染非常简单,因此我将扩展DefaultTreeCellRenderer
并覆盖其getTreeCellRendererComponent
方法.您可以简单地在DefaultTreeCellRenderer
使用的JLabel
上调整前景色.这是一个简单的示例:
Since the custom rendering you want to do is pretty basic, I would just extend DefaultTreeCellRenderer
and override its getTreeCellRendererComponent
method. You could simply adjust the foreground color on the JLabel
that the DefaultTreeCellRenderer
uses. Here's a quick example:
tree.setCellRenderer(new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
JLabel label = (JLabel)super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
YourNode node = (YourNode)value;
if (node.isFlagged())
label.setForeground(Color.RED);
return label;
}
});
结果:
这篇关于根据节点中存储的数据突出显示jtree中的特定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!