[Java]Swing树状组件JTree

一 简单样式

TreeNodeDemo.java

package com.sjf;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeNodeDemo {

    public static void main(String[] args) {

        // 创建没有父节点和子节点、但允许有子节点的树节点,并使用指定的用户对象对它进行初始化。
        // public DefaultMutableTreeNode(Object userObject)
        DefaultMutableTreeNode group1 = new DefaultMutableTreeNode("软件部");

        TreeNode node1 = new TreeNode();
        node1.setName("王雨");
        node1.setNickName("漫天飞舞");
        group1.add(new DefaultMutableTreeNode(node1));

        TreeNode node2 = new TreeNode();
        node2.setName("陈梦");
        node2.setNickName("梦");
        group1.add(new DefaultMutableTreeNode(node2));

        TreeNode node3 = new TreeNode();
        node3.setName("上官飞儿");
        node3.setNickName("飞儿");
        group1.add(new DefaultMutableTreeNode(node3));

        DefaultMutableTreeNode group2 = new DefaultMutableTreeNode("销售部");

        TreeNode node4 = new TreeNode();
        node4.setName("上官婉儿");
        node4.setNickName("婉儿");
        group2.add(new DefaultMutableTreeNode(node4));

        TreeNode node5 = new TreeNode();
        node5.setName("上官巧儿");
        node5.setNickName("巧儿");
        group2.add(new DefaultMutableTreeNode(node5));

        DefaultMutableTreeNode top = new DefaultMutableTreeNode("职员管理");

        top.add(group1);
        top.add(group2);

        final JTree tree = new JTree(top);
        JFrame f = new JFrame("JTreeDemo");
        f.add(tree);
        f.setSize(300, 300);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 添加选择事件
        tree.addTreeSelectionListener(new TreeSelectionListener()
        {
            @Override
            public void valueChanged(TreeSelectionEvent e)
            {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (node == null){
                    return;
                }//if

                Object object = node.getUserObject();
                TreeNode user = (TreeNode) object;
                System.out.println("你选择了:" + user.toString());
            }
        });
    }
}

TreeNode.java

package com.sjf;

public class TreeNode {
    private String nickName = "";
    private String name = "";
    private String phone = "";
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    // 重点在toString,节点的显示文本就是toString
    public String toString()
    {
        return name + "["+nickName+"]";
    }
}

二 图标样式

TreeNode.java

package com.sjf;

public class TreeNode {
    private String nickName = "";
    private String name = "";
    private String phone = "";
    private int age;
    private String imagePath = "";

    public String getImagePath() {
        return imagePath;
    }
    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    // 重点在toString,节点的显示文本就是toString
    public String toString()
    {
        return name + "["+nickName+"]";
    }
}

TreeCellRenderer.java

package com.sjf;

import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

/**
 * 自定义树描述类,将树的每个节点设置成不同的图标
 *
 */
public class TreeCellRenderer extends DefaultTreeCellRenderer{

    private static final long   serialVersionUID    = 1L;
    /**
     * 重写父类DefaultTreeCellRenderer的方法
     */
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean selected, boolean expanded, boolean isLeaf, int row,boolean hasFocus)
    {
        // 选中
        if (selected)
        {
            setForeground(getTextSelectionColor());
        }
        else
        {
            setForeground(getTextNonSelectionColor());
        }
        // TreeNode
        DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) value;

        Object obj = treeNode.getUserObject();

        if (obj instanceof TreeNode)
        {
            TreeNode node = (TreeNode) obj;
            DefaultTreeCellRenderer tempCellRenderer = new DefaultTreeCellRenderer();
            tempCellRenderer.setLeafIcon(new ImageIcon(node.getImagePath()));
            return tempCellRenderer.getTreeCellRendererComponent(tree, node.toString(), selected, expanded, true, row, hasFocus);
        }
        else if (obj instanceof String)
        {
            String text = (String) obj;
            DefaultTreeCellRenderer tempCellRenderer = new DefaultTreeCellRenderer();
            tempCellRenderer.setOpenIcon(new ImageIcon("Image/open.jpg"));
            tempCellRenderer.setClosedIcon(new ImageIcon("Image/close.jpg"));
            return tempCellRenderer.getTreeCellRendererComponent(tree, text, selected, expanded, false, row, hasFocus);
        }
        return super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, hasFocus);
    }
}

TreeNodeDemo.java

package com.sjf;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeNodeDemo {

    public static void main(String[] args) {

        // 创建没有父节点和子节点、但允许有子节点的树节点,并使用指定的用户对象对它进行初始化。
        // public DefaultMutableTreeNode(Object userObject)
        DefaultMutableTreeNode group1 = new DefaultMutableTreeNode("软件部");

        TreeNode node1 = new TreeNode();
        node1.setName("王雨");
        node1.setNickName("漫天飞舞");
        node1.setImagePath("Image/1.jpg");
        group1.add(new DefaultMutableTreeNode(node1));

        TreeNode node2 = new TreeNode();
        node2.setName("陈梦");
        node2.setNickName("梦");
        node2.setImagePath("Image/2.jpg");
        group1.add(new DefaultMutableTreeNode(node2));

        TreeNode node3 = new TreeNode();
        node3.setName("上官飞儿");
        node3.setNickName("飞儿");
        node3.setImagePath("Image/3.jpg");
        group1.add(new DefaultMutableTreeNode(node3));

        DefaultMutableTreeNode group2 = new DefaultMutableTreeNode("销售部");

        TreeNode node4 = new TreeNode();
        node4.setName("上官婉儿");
        node4.setNickName("婉儿");
        node4.setImagePath("Image/4.jpg");
        group2.add(new DefaultMutableTreeNode(node4));

        TreeNode node5 = new TreeNode();
        node5.setName("上官巧儿");
        node5.setNickName("巧儿");
        node5.setImagePath("Image/5.jpg");
        group2.add(new DefaultMutableTreeNode(node5));

        DefaultMutableTreeNode root = new DefaultMutableTreeNode();
        root.add(group1);
        root.add(group2);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        final JTree tree = new JTree(root);
        tree.setCellRenderer(new TreeCellRenderer());
        tree.putClientProperty("JTree.lineStyle", "None");
        tree.setRootVisible(false);

        JFrame frame = new JFrame("JTreeDemo");
        frame.add(tree);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        // 添加选择事件
        tree.addTreeSelectionListener(new TreeSelectionListener()
        {
            @Override
            public void valueChanged(TreeSelectionEvent e)
            {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (node == null){
                    return;
                }//if

                Object object = node.getUserObject();
                if(object instanceof TreeNode)
                {
                    TreeNode user = (TreeNode) object;
                    System.out.println("你点击了:" + user.toString());
                }
                else if(object instanceof String)
                {
                    String text = (String)object;
                    System.out.println("你点击了:" + text);
                }
            }
        });
    }
}

时间: 2024-10-12 07:57:48

[Java]Swing树状组件JTree的相关文章

Java Swing 树状组件JTree的使用方法(转)

树中特定的节点可以由 TreePath(封装节点及其所有祖先的对象)标识,或由其显示行(其中显示区域中的每一行都显示一个节点)标识.展开 节点是一个非叶节点(由返回 false 的 TreeModel.isLeaf(node) 标识),当展开 其所有祖先时,该节点将显示其子节点.折叠 节点是隐藏它们的节点.隐藏 节点是位于折叠祖先下面的节点.所有可查看 节点的父节点都是可以展开的,但是可以显示它们,也可以不显示它们.显示 节点是可查看的并且位于可以看到它的显示区域. 构造方法摘要 JTree()

Java文件目录树状结构:控制台打印某个文件夹下的文件目录树状结构

1 package com.zhen.file; 2 3 import java.io.File; 4 5 /* 6 * 控制台打印某个文件夹下的文件目录树状结构 7 * 递归算法 8 */ 9 10 public class FileTree { 11 12 public static void main(String[] args) { 13 File file =new File("D:/Github/JavaTest"); 14 PrintFile(file, 0); 15 }

【Java Swing探索之路系列】之二:Java Swing布局面板组件

作者:郭嘉 邮箱:[email protected] 博客:http://blog.csdn.net/allenwells github:https://github.com/AllenWell 面板指的是容器,即中间容器类,可以将基本组件放置在其中,组成丰富多彩的用户界面. 一 JPanel 在JPanel的使用中,有一个双缓冲的概念,这个技术旨在改进频繁变化的组件显示效果.可以在JPanel初始化的时候进行定义如下所示: 举例 展示如何使用JPanel中间容器类. import javax.

Java Swing编程之仿js树状折叠菜单

最近要完成一个需求:用swing做个树状菜单,含二级菜单,点击一级菜单展开二级菜单,且二级菜单数目超过预览视图会出现滚动条.由于swing研究的少,花了不少精力! 先看下测试效果图: 收起图: 展开图: 完整源码: 1 package com.xuwei.test2; 2 3 import java.awt.BorderLayout; 4 import java.awt.Color; 5 import java.awt.GridLayout; 6 import java.awt.event.Ac

JAVA学习Swing章节按钮组件JButton的简单学习

package com.swing; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.Icon; import javax.swing.ImageIcon;

vue 用组件的方式渲染树状数据结构新思路

应用场景是这样的,根据客户选择城市(树状结构,大概如下所示):展示到页面,也就是说会与好多层,甚至不确定的情况,一开始选择的方式逐层判断,一层层的遍历,然后后来放弃了,想到了写菜单组件的时候使用过的组件 --- 递归组件对没错,这里只需要把数据展开显示就好了,然后就愉快的啪啪啪了,而且不用担心嵌套层次太深,代码结构也相对之前的逐层遍历要简洁: [ { "id": 1, "text": "A", "children": [ {

[shyのJAVA初探]hdu1166●树状数组

一开始shy是为了大数而走近java,随后情不自禁地就希望能初步了解java的语言特点. java初学对c++选手而言可谓简单非常.因为java的语法和c++的语法简直一样(虽然这话不太严谨,容易遭到很多反驳,不过,,shy实在是没有见过如此相像的两种语言).比如,①java开变量的方式是:int x;char c;boolean b;②java的for循环:for(int i=1;i<=n;i++){}③java的条件语句:if(--cas>0&&str!="end

Java Swing界面编程(3)---标签组件(JLabel)

package com.beyole.util; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import javax.swing.JFrame; import javax.swing.JLabel; public class test2 { public static void main(String[] args) { JFrame frame =

Java Swing界面编程(17)---单行文本输入组件:JTextField

package com.beyole.util; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class test15 { public static void main(String[] args) { JFrame frame = new JFrame("Crystal");// 实例化窗