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.
If the field is true
, then I would like it to be highlighted in red, otherwise no highlighting.
What is a good way to accomplish this? Should I extend DefaultTreeCellRenderer
? Implement my own custom TreeCellRenderer
? Some other method?
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;
}
});
And the result: