Ein einfaches Beispiel für einen JTree, bei welchem die Nodes individuelle Icons erhalten:
package com.sowas.icontree.javawiki; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import java.awt.BorderLayout; public class IconTreeDemo extends JFrame { public IconTreeDemo() { super("Icon Tree Demo"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new BorderLayout()); ImageIcon iconRoot = new ImageIcon(getClass().getResource("images/iconRoot.png")); IconTreeNode root = new IconTreeNode(iconRoot, "Root"); ImageIcon iconLeaf1 = new ImageIcon(getClass().getResource("images/iconLeaf1.png")); root.add(new IconTreeNode(iconLeaf1, "Leaf 1")); ImageIcon iconLeaf2 = new ImageIcon(getClass().getResource("images/iconLeaf2.png")); root.add(new IconTreeNode(iconLeaf2, "Leaf 2")); JTree tree = new JTree(root); tree.setCellRenderer(new IconTreeNodeRenderer()); JScrollPane scrollPane = new JScrollPane(tree); getContentPane().add(scrollPane, BorderLayout.CENTER); setSize(400, 300); setLocationRelativeTo(null); } public static void main(String args[]) { IconTreeDemo ptd = new IconTreeDemo(); ptd.setVisible(true); } }
package com.sowas.icontree.javawiki; import javax.swing.Icon; import javax.swing.tree.DefaultMutableTreeNode; public class IconTreeNode extends DefaultMutableTreeNode { public IconTreeNode(Icon icon, String text) { super(text); setUserObject(new TreeNodeData(icon, text)); } class TreeNodeData { Icon icon; String text; public TreeNodeData(Icon icon, String text) { this.icon = icon; this.text = text; } public Icon getIcon() { return icon; } public void setIcon(Icon icon) { this.icon = icon; } public String getText() { return text; } public void setText(String text) { this.text = text; } } }
package com.sowas.icontree.javawiki; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.Component; public class IconTreeNodeRenderer extends DefaultTreeCellRenderer { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { IconTreeNode.TreeNodeData data = (IconTreeNode.TreeNodeData) ((IconTreeNode) value).getUserObject(); setIcon(data.getIcon()); setText(data.getText()); return this; } }