我想为JTree的特定节点着色(并给出一个图标),而不是像OpenNode,LeafNode等那样的组。我该怎么做呢?
答案 0 :(得分:2)
This tutorial展示了如何设置自己的节点图标以及如何区分树中的叶子和非叶子。
答案 1 :(得分:0)
最简单的方法是使用JTree
构建DefaultMutableTreeNode
模型并设置某些节点的“用户对象”值,然后使用此值确定渲染器遇到该节点时的行为。
首先,我们构造一个简单模型并将其传递给JTree
构造函数:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Hello");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Goodbye");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Bonjour");
root.add(child1);
root.add(child2);
JTree tree = new JTree(root);
现在定义自定义树单元格渲染器:
TreeCellRenderer renderer = new DefaultTreeCellRenderer() {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
// Defer to superclass to create initial version of JLabel and then modify (below).
JLabel ret = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
// We know that value is a DefaultMutableTreeNode so this downcast is safe.
MutableTreeNode node = (MutableTreeNode) value;
// Inspect user object and change rendering based on this.
if ("Hello".equals(node.getUserObject())) {
ret.setIcon(...);
}
// Could also inspect whether node is a leaf node, etc.
return ret;
}
};