java JTree树 叶子节点 不同图标

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; } }

你可能感兴趣的:(java,String,object,tree,Class,jcomponent)