最近为一个程序写界面,需要更换JTree的默认图标,因为以前从没做过swing,走了不少弯路,现在把方法告诉大家,希望对你的工作能有所帮助.
先来一个常见的图标更换方法,需要显示继承DefaultTreeCellRenderer类,代码引用自http://blog.blogchina.com/174500.html
private class MyRenderer extends DefaultTreeCellRenderer {
ImageIcon htmlIcon;
ImageIcon imageIcon;
public MyRenderer() {
htmlIcon = new ImageIcon("source/html.gif");
imageIcon=new ImageIcon("source/image.gif");
}
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
if (leaf && isImage(value)) {
setIcon(imageIcon);
//setToolTipText("This book is in the Tutorial series.");
}
else if(leaf){
setIcon(htmlIcon);
}
return this;
}
protected boolean isImage(Object value) {
Sitemarks.SitemarkEntry node =
(Sitemarks.SitemarkEntry)value;
String name=
(String)(node.getName());
if (name.endsWith(".jpg")||name.endsWith(".gif")) {
return true;
}
return false;
}
}
实现起来太麻烦了,我只是想换个图标而已,java也太不讲人情了,需要写这么多代码.于是我尝试这样直接设置:
JTree leftTree = new JTree();
((DefaultTreeCellRenderer)leftTree.getCellRenderer()).setClosedIcon(myClosedIcon);
这样的问题是,如果你需要动态增删JTree的结点,调用UpdateUI()方法后,显示的图标又变为默认的图标.你还得在调用updateUI()后重新调用上面语句.
最后我想到使用匿名类的方法如下:
leftTree.setCellRenderer(new DefaultTreeCellRenderer(){
public Icon getClosedIcon() {
//返回你需要的图标
return myClosedIcon
}
});