java 如何更改单个 JTree 节点的样式(颜色、字体)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10111849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change style (color, font) of a single JTree node
提问by soumitra chatterjee
I have two JTree
in two panels in a JFrame
. I want to change the style(color and font) of nodes on drag and drop from one tree to the other.Please provide me a way to change the color of a JTree
node permanently.
我有两个JTree
面板中的两个JFrame
。我想在从一棵树拖放到另一棵树时更改节点的样式(颜色和字体)。请为我提供一种JTree
永久更改节点颜色的方法。
回答by ControlAltDel
To start, you will need to have a data object that can handle style and color. You could subclass DefaultMutableTreeNode and add these data items with getts and setters
首先,您需要有一个可以处理样式和颜色的数据对象。您可以继承 DefaultMutableTreeNode 并使用 getts 和 setter 添加这些数据项
Then you'd need to create a custom TreeCellRenderer. I recommend extending DefaultTreeCellRenderer, and in the overridden handler, checking for your custom class, and modifying the JLabel output to use the Font and Color if these values are set
然后你需要创建一个自定义的 TreeCellRenderer。我建议扩展 DefaultTreeCellRenderer,并在覆盖的处理程序中检查您的自定义类,并修改 JLabel 输出以使用 Font 和 Color(如果设置了这些值)
回答by Stéphane Bruckert
Create your own CellRenderer
. To give the appropriate behaviour to your MyTreeCellRenderer
, you will have to extend DefaultTreecellRenderer
and override the getTreeCellRendererComponent
method.
创建您自己的CellRenderer
. 要为您的 提供适当的行为MyTreeCellRenderer
,您必须扩展DefaultTreecellRenderer
和覆盖该getTreeCellRendererComponent
方法。
public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
// Assuming you have a tree of Strings
String node = (String) ((DefaultMutableTreeNode) value).getUserObject();
// If the node is a leaf and ends with "xxx"
if (leaf && node.endsWith("xxx")) {
// Paint the node in blue
setForeground(new Color(13, 57 ,115));
}
return this;
}
}
Finally, say your tree is called myTree
, set your CellRenderer
to it:
最后,说你的树被称为myTree
,设置你的CellRenderer
:
myTree.setCellRenderer(new MyTreeCellRenderer());