gpt4 book ai didi

java - JTree多节点渲染器问题

转载 作者:行者123 更新时间:2023-12-01 05:58:27 25 4
gpt4 key购买 nike

在下面的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;
}
}

最佳答案

是的,在getTreeCellRendererComponent中,您需要查阅value并使用适当的图像调用setIcon()

注意:默认实现会查看 expandedleaf 的值,以在打开、关闭或叶子图标之间进行选择。

关于java - JTree多节点渲染器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com