浏览 2900 次
锁定老帖子 主题:整理swing之JTree渲染(1)
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2009-04-06
/** * 树控件使用 * @author lgh */ public class JTreeTest extends JFrame { public JTreeTest() { init(); } private void init() { this.setSize(800, 600); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); this.add(createJTree(), BorderLayout.CENTER); this.setVisible(true); } /** * 创建一个树 * @return */ private JScrollPane createJTree() { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); node.setUserObject(new MyTreeNode(new ImageIcon(Pic.tree2), "root")); JTree jt = new JTree(node); jt.setCellRenderer(new MyTreeCellRenderer()); createRootMutableTreeNode(node); JScrollPane jsp = new JScrollPane(jt); return jsp; } private void createRootMutableTreeNode(DefaultMutableTreeNode root) { root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node1"))); root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node2"))); root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node3"))); root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node4"))); root.add(new DefaultMutableTreeNode(new MyTreeNode(new ImageIcon(Pic.tree1), "node5"))); } public static void main(String[] args) { JTreeTest jTreeTest = new JTreeTest(); } private class MyTreeCellRenderer extends DefaultTreeCellRenderer { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; MyTreeNode jtreeNode = (MyTreeNode) node.getUserObject(); this.setIcon(jtreeNode.getIcon()); this.setText(jtreeNode.getName()); this.setOpaque(true); if (selected) { this.setBackground(new Color(178, 180, 191)); } else { this.setBackground(new Color(255, 255, 255)); } return this; } } private class MyTreeNode extends DefaultMutableTreeNode { private Icon icon; private String name; public MyTreeNode(Icon icon, String name) { this.icon = icon; this.name = name; } public MyTreeNode() { super(); } /** * @return the icon */ public Icon getIcon() { return icon; } /** * @param icon the icon to set */ public void setIcon(Icon icon) { this.icon = icon; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } } }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-04-06
....渲染?用了好大一个帽子
|
|
返回顶楼 | |
发表时间:2009-04-06
ray_linn 写道 ....渲染?用了好大一个帽子
呵呵,海纳百川,有容乃大.帽子虽大,是为了后面的扩展. |
|
返回顶楼 | |