java树节点显示不同的图标_java JTree树 叶子节点 不同图标

本文介绍了如何在Java中使用`JTree`组件显示不同类型的图标。通过创建自定义的`DefaultTreeCellRenderer`子类`MyTreeCellRender`,设置叶子节点的图标,并根据节点类型(如“用户”或“组”)来决定显示不同的图标。同时,创建了`JTreeData`类来存储节点的文本和图标信息。
摘要由CSDN通过智能技术生成

1.设置树的映射关系

DefaultTreeCellRenderer myCellRenderer = new MyTreeCellRender();

//设置叶子节点的图标

jTree.setCellRenderer(myCellRenderer);

2.调用,具体查看JTreeData结构

DefaultMutableTreeNode leafUserNode = new DefaultMutableTreeNode(new JTreeData("string",new ImageIcon("")));

3. MyTreeCellRender.java

public class MyTreeCellRender extends DefaultTreeCellRenderer

{

//定义图标和要显示的字符串

ImageIcon icon = null;

String str = null;

/* (non-Javadoc)

* @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean)

*/

@Override

public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)

{

// TODO Auto-generated method stub

super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,

row, hasFocus);

DefaultMutableTreeNode node=(DefaultMutableTreeNode)value;

if(node.isLeaf()&&node.getParent().toString().equals("用户"))

{

JTreeData jtd = (JTreeData)node.getUserObject();

setIcon(jtd.getIcon());

setText(jtd.getString());

return this;

}

if(node.isLeaf()&&node.getParent().toString().equals("组"))

{

JTreeData jtd = (JTreeData)node.getUserObject();

setIcon(jtd.getIcon());

setText(jtd.getString());

return this;

}

return this;

}

}

4.JTreeData.java

public class JTreeData

{

private String strNode;

private ImageIcon iconNode;

private JComponent jcp;

public JTreeData(String str, ImageIcon icon)

{

strNode = str;

iconNode = icon;

}

public JTreeData(String str)

{

strNode = str;

}

public String getString()

{

return strNode;

}

public void setString(String strNode)

{

this.strNode = strNode;

}

public ImageIcon getIcon()

{

return iconNode;

}

public void setIcon(ImageIcon iconNode)

{

this.iconNode = iconNode;

}

/**

* @return the jcp

*/

public JComponent getJcp()

{

return jcp;

}

/**

* @param jcp the jcp to set

*/

public void setJcp(JComponent jcp)

{

this.jcp = jcp;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值