[英]How to change background color of a jtree node
I am having a.netbeans project with jtree and DefaultMutableTreeNode.我有一个带有 jtree 和 DefaultMutableTreeNode 的 .netbeans 项目。 I have to search a node in the tree by its name and want to highlight it, for highlighting I think I will change the background color of the node.
我必须按名称在树中搜索节点并想要突出显示它,为了突出显示我想我会更改节点的背景颜色。
For searching the node I made a func, `为了搜索节点,我做了一个函数,`
public DefaultMutableTreeNode searchNode(DefaultMutableTreeNode treeRoot, String nodeStr) {
DefaultMutableTreeNode node = null;
Enumeration e = treeRoot.breadthFirstEnumeration();
while (e.hasMoreElements()) {
node = (DefaultMutableTreeNode) e.nextElement();
if (nodeStr.equals(node.getUserObject().toString())) {
return node;
}
}
return null;
}
now I can search a desired node by its name,
DefaultMutableTreeNode searched = searchNode(root, "mynode");` now I can search a desired node by its name,
DefaultMutableTreeNode searched = searchNode(root, "mynode");`
it gives me the node but now I am stuck how to highlight the searched node returned by this function, I need to make something like, searched.changeBackgroundColor(Color.RED);
它给了我节点,但现在我不知道如何突出显示这个 function 返回的搜索节点,我需要做一些类似的东西,
searched.changeBackgroundColor(Color.RED);
to highlight the searched node.突出显示搜索到的节点。
Please help me to do it.请帮我做。 Thanks
谢谢
The model, in this case DefaultMutableTreeNode
, doesn't do its own rendering. model(在本例中为
DefaultMutableTreeNode
)不进行自己的渲染。 It's just for storing data.它只是用于存储数据。
All rendering is done through implementations of TreeCellRenderer .所有渲染都是通过TreeCellRenderer的实现完成的。 There is one provided implementation, DefaultTreeCellRenderer .
提供了一个实现DefaultTreeCellRenderer 。
The best way to go forward is to create a sub class of DefaultTreeCellRenderer
, and override its getTreeCellRendererComponent
method. go 转发的最佳方法是创建
DefaultTreeCellRenderer
的子 class,并覆盖其getTreeCellRendererComponent
方法。 For example:例如:
public Component getTreeCellRendererComponent(JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
Component component = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value == searched) {
component.setBackground(Color.RED);
}
return component;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.