Highlighting specific nodes in a jtree depending on data stored in the node

大兔子大兔子 提交于 2019-12-11 20:33:16

问题


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?


回答1:


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:



来源:https://stackoverflow.com/questions/17111483/highlighting-specific-nodes-in-a-jtree-depending-on-data-stored-in-the-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!