关注多个教程和问题,例如this或this 我正在尝试创建一个Jtree dom,它应该能够根据应用程序中设置的属性设置不同的图标,但我无法找到一种方法来正确设置图标,因为它在设置后显示不正确
我创建了自己的类XML_JTRE_ELEM
,它将JTree作为超类,并实现了TreeExpansionListener
覆盖的扩展方法如下所示
public void treeExpanded(TreeExpansionEvent event) {
TreePath path = event.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
XML_JTREE_ELEM elem = (XML_JTREE_ELEM)node.getUserObject(); // Get the current JTREE
for(String key : elem.getSubTrees().keySet()) {
// Set the icon dynamcally for each subtree item
elem.getSubTrees().get(key).setIcon();
}
}
setIcon方法只为每个子树设置一个新的CellRenderer
public void setIcon() {
DefaultTreeCellRenderer renderer = new TagRenderer(ImageList.sum);
this.setCellRenderer(renderer);
}
CellRenderer本身如下所示:
private class TagRenderer extends DefaultTreeCellRenderer{
private static final long serialVersionUID = 1L;
private ImageIcon _icon;
public TagRenderer(ImageIcon icon) {
this._icon = icon;
}
@Override
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean selected, boolean expanded,
boolean isLeaf, int row, boolean focused) {
setIcon(_icon);
System.out.Println(_icon.toString());
return this;
}
}
当我打印_icon时,我得到预期的结果file:/C:/java_ws/project/bin/resources/Sum.png
我得到的输出如下所示:
但根据调试消息,它正在为Test
Jtree下的每个JTree元素设置正确的图标。我是否需要在设置图标后重新加载JTree的模型,或者通常是将图标设置为错误的方法?