package itheima011; import org.w3c.dom.Node; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.*; public class DefaultTreeCellRendererDemo2 { public static void main(String[] args) { new DefaultTreeCellRendererDemo2().init(); } JFrame jf = new JFrame("DefaultTreeCellRenderer扩展类型"); JTree tree; ImageIcon image = new ImageIcon("myawt\\img\\王宪林.jpg"); ImageIcon image2 = new ImageIcon("myawt\\img\\何猷君.jpg"); ImageIcon image3 = new ImageIcon("myawt\\img\\李清照.jpg"); ImageIcon image4 = new ImageIcon("myawt\\img\\王宪林.jpg"); String name = new String("根节点"); private class NodeData { private ImageIcon image; private String name; public ImageIcon getImage() { return image; } public void setImage(ImageIcon image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } public NodeData(ImageIcon image, String name) { this.image = image; this.name = name; } } DefaultMutableTreeNode root = new DefaultMutableTreeNode(new NodeData(image, name)); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(new NodeData(image2, name)); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(new NodeData(image3, name)); DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(new NodeData(image4, name)); DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(new NodeData(image4, name)); DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(new NodeData(image2, name)); DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(new NodeData(image3, name)); private class MyRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; NodeData userObject = (NodeData) node.getUserObject(); String name = userObject.getName(); ImageIcon image = userObject.getImage(); this.setText(name); this.setIcon(image); return this; } } private void init() { node1.add(node2); node1.add(node3); node4.add(node5); node4.add(node6); root.add(node1); root.add(node4); tree=new JTree(root); tree.setCellRenderer(new MyRenderer()); jf.add(new JScrollPane(tree)); jf.pack(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } }
使用继承DefaultTreeCellRenderer的类,改变结点外观
于 2023-12-05 21:09:48 首次发布
本文展示了如何在JavaSwing中使用DefaultTreeCellRenderer自定义JTree的节点渲染,包括设置图标和文本。作者通过创建一个扩展类MyRenderer实现个性化节点显示。
摘要由CSDN通过智能技术生成