在以下 JTreeBasics.java 文件中,是否可以为BlackBox和WhiteBox节点提供不同的图像?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.lang.reflect.*;
public class JTreeBasics{
JFrame f;
DefaultMutableTreeNode root,n1,n2,ln1,ln2,ln3,ln4,ln3_1,ln3_2,ln3_1_1,ln3_1_2,ln3_1_2_1;
DefaultTreeModel dtm;
JTree tree;
public JTreeBasics() {
f=new JFrame("JTree Demo");
f.setSize(400, 500) ;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
root=new DefaultMutableTreeNode("BlackBox");
n1=new DefaultMutableTreeNode("WhiteBox");
root.add(n1);
ln1=new DefaultMutableTreeNode("Item");
n1.add(ln1);
n2=new DefaultMutableTreeNode("BlackBox");
root.add(n2);
ln2=new DefaultMutableTreeNode("Item");
n2.add(ln2);
ln3=new DefaultMutableTreeNode("WhiteBox");
n2.add(ln3);
ln3_1=new DefaultMutableTreeNode("WhiteBox");
ln3_1_1=new DefaultMutableTreeNode("Item");
ln3_1.add(ln3_1_1);
ln3_1_2=new DefaultMutableTreeNode("BlackBox");
ln3_1_2_1=new DefaultMutableTreeNode("Item");
ln3_1_2.add(ln3_1_2_1);
ln3_1.add(ln3_1_2);
ln3.add(ln3_1);
ln3_2=new DefaultMutableTreeNode("Item");
ln3.add(ln3_2);
ln4=new DefaultMutableTreeNode("Item");
n2.add(ln4);
dtm=new DefaultTreeModel(root);
tree=new JTree(dtm);
//most imp. line of this code
installingCustomRenderer() ;
f.add(tree);
f.setVisible(true);
}
private void installingCustomRenderer(){
CustomTreeCellRenderer renderer = new CustomTreeCellRenderer();
tree.setCellRenderer(renderer);
}
public static void main(String[] args){
new JTreeBasics();
}
}
class CustomTreeCellRenderer extends DefaultTreeCellRenderer{
private Font plainFont = null;
private Font italicFont = null;
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus){
super.getTreeCellRendererComponent(tree, value,
selected, expanded, leaf, row, hasFocus);
plainFont = getFont();
italicFont = plainFont.deriveFont(Font.ITALIC) ;
setFont(italicFont);
return this;
}
}
答案 0 :(得分:0)
是的,在getTreeCellRendererComponent
中,您需要咨询value
并使用适当的图片致电setIcon()
。
注意:默认实现会查看expanded
和leaf
的值,以便在打开,关闭或叶子图标之间进行选择。
答案 1 :(得分:0)
在渲染器代码中,将超级调用的返回值强制转换为JLabel(因为DefaultTreeCellRenderer 是一个JLabel),然后根据'value'可以对其进行setIcon()。< / p>