我创建了一个 JTree,即使有多个根节点(这对我来说相当困难,因为这是我的第一个 JTree),并且准备好(我想)更进一步;一个细胞渲染器。
我尝试为每个节点设置一个图标,效果很好。现在我正在尝试检查它是什么类型的节点(不仅是叶子和分支),并构建我想要的图像文件名的字符串。isKlas()
现在总是返回 true,所以它应该是 klas_fold.png 或 klas_unfold.png。但是getTreeCellRendererComponent()
只是部分执行,因为文件路径永远不会被打印,也没有任何图标更改,它始终是默认值!
这是我的代码:
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class RATree extends JTree {
private static final long serialVersionUID = -3855798479619346917L;
public RATree(Object[] top) {
super(top);
MyRenderer renderer = new MyRenderer();
this.setCellRenderer(renderer);
setBorder(BorderFactory.createRaisedBevelBorder());
}
protected ImageIcon createImageIcon(String path) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
class MyRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
TreeItem node;
String fileName = "";
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
try {
node = (TreeItem) value;
}
catch (ClassCastException ex)
{
ex.printStackTrace();
return this;
}
if(node.isKlas()) {
fileName += "klas_";
}
if(expanded) {
fileName += "unfold.png";
this.setIcon(createImageIcon("../bin/" + fileName));
}
else {
fileName += "fold.png";
this.setIcon(createImageIcon("../bin/" + fileName));
}
System.out.println("fileName: " + fileName); //Doesn't get executed, or at least, I can't see it.
return this;
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Short, Self Contained, Correct (Compilable), Example");
Object[] root = {new TreeItem("name", "someURL"), new TreeItem("name", "someUrl")};
f.add(new RATree(root));
f.setSize(100,100);
f.setVisible(true);
}
}
是的,它是一个内部类。
谢谢!
编辑:
我发现这是一个 ClassCastException 搞砸了事情。但这很奇怪,因为我像这样初始化 Tree new JTree({new TreeItem("params"), new TreeItem("params")});
:所以我应该能够将它们从 Object 转换回 TreeItem?(TreeItem 是我的类之一。它扩展了 DefaultMutableTreeNode)。