JTree

http://www.easyicon.net/

package swing.tree;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.util.Enumeration;

import javax.lang.model.element.Modifier;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/*2015-7-11*/
public class ClassTree {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ClassTreeFrame frame = new ClassTreeFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);
            }
        });

    }

}

class ClassTreeFrame extends JFrame {
    private static final long serialVersionUID = 3866055150465649395L;

    private DefaultMutableTreeNode root;
    private DefaultTreeModel model;
    private JTree tree;
    private JTextField textField;
    private JTextArea textArea;
    private static final int DEFAULT_WIDTH = 800;
    private static final int DEFAULT_HEIGHT = 600;

    public ClassTreeFrame() {
        setTitle(getClass().getSimpleName());
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        root = new DefaultMutableTreeNode(java.lang.Object.class);
        model = new DefaultTreeModel(root);
        tree = new JTree(model);

        addClass(getClass());

        ClassNameTreeCellRender render = new ClassNameTreeCellRender();
        String filename = getClass().getResource("/swing/tree/red-ball.gif").getPath();
        render.setClosedIcon(new ImageIcon(filename));
        filename = getClass().getResource("/swing/tree/yellow-ball.gif").getPath();
        render.setOpenIcon(new ImageIcon(filename));
        filename = getClass().getResource("/swing/tree/blue-ball.gif").getPath();
        render.setLeafIcon(new ImageIcon(filename));
        tree.setCellRenderer(render);

        tree.addTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {

                TreePath path = tree.getSelectionPath();
                if (path == null) {
                    return;
                }
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
                Class<?> c = (Class<?>) selectedNode.getUserObject();
                String description = getFileDescription(c);
                textArea.setText(description);
            }
        });

        int mode = TreeSelectionModel.SINGLE_TREE_SELECTION;
        tree.getSelectionModel().setSelectionMode(mode);

        textArea = new JTextArea();

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 2));
        panel.add(new JScrollPane(tree));
        panel.add(new JScrollPane(textArea));

        add(panel, BorderLayout.CENTER);

        addTextField();

    }

    private void addTextField() {
        JPanel panel = new JPanel();
        ActionListener addListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String text = textField.getText();
                    addClass(Class.forName(text));
                    textField.setText("");
                } catch (ClassNotFoundException e1) {
                    JOptionPane.showMessageDialog(ClassTreeFrame.this, e1.getMessage());
                }
            }
        };

        textField = new JTextField(20);
        textField.addActionListener(addListener);
        panel.add(textField);

        JButton addButton = new JButton("Add");
        addButton.addActionListener(addListener);
        panel.add(addButton);
        add(panel, BorderLayout.SOUTH);

    }

    protected String getFileDescription(Class<?> c) {
        StringBuilder r = new StringBuilder();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            if (field.getModifiers() == Modifier.STATIC.ordinal()) {
                r.append("static");
            }
            r.append(field.getType().getName())
                    .append("")
                    .append(field.getName())
                    .append("\n");

        }

        return r.toString();
    }

    private DefaultMutableTreeNode addClass(Class<?> c) {
        if (c.isInterface() || c.isPrimitive()) {
            return null;
        }

        DefaultMutableTreeNode node = findUserObject(c);
        if (node != null) {
            return node;
        }

        Class<?> s = c.getSuperclass();
        DefaultMutableTreeNode parent;
        if (s == null) {
            parent = root;
        } else {
            parent = addClass(s);
        }

        DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(c);
        model.insertNodeInto(newChild, parent, parent.getChildCount());

        TreePath path = new TreePath(model.getPathToRoot(newChild));
        tree.makeVisible(path);
        return newChild;
    }

    private DefaultMutableTreeNode findUserObject(Object obj) {
        @SuppressWarnings("unchecked")
        Enumeration<TreeNode> e = root.breadthFirstEnumeration();
        while (e.hasMoreElements()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
            if (node.getUserObject().equals(obj)) {
                return node;
            }
        }
        return null;
    }

}

class ClassNameTreeCellRender extends DefaultTreeCellRenderer {
    private static final long serialVersionUID = -2145290206168596413L;
    private Font plainFont;
    private Font italicFont;

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
            boolean expanded, boolean leaf, int row, boolean hasFocus) {

        Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

        DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
        Class<?> c = (Class<?>) node.getUserObject();

        if (plainFont == null) {
            plainFont = getFont();
            if (plainFont == null) {
                italicFont = plainFont.deriveFont(Font.ITALIC);
            }
        }

        if (c.getModifiers() == Modifier.ABSTRACT.ordinal()) {
            setFont(plainFont);
        } else {
            comp.setFont(italicFont);
        }

        return comp;
    }

}
时间: 2024-10-12 13:27:13

JTree的相关文章

JTree 添加 , 删除, 修改

package com.swing.demo; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.CellEdi

JTree 常用方法

package com.swing.demo; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.swing.JFrame; import javax.swing.JS

[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 T

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

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

Jtree(节点的渲染+资源管理器)(2)

上一次我们建立一个比较简单的资源管理器,这次我们说一下上面的资源管理器的问题,并且得尽量的贴近windows的资源管理器. 这样一个简单的资源管理树就完成了,下面我们说说它的问题: ① 图片和外观和Windows有差距 这个我们可以通过设置L&F和通过前面写的Renderer那样设置新的图片解决,不是大问题. ② 文件夹里文件多时展开会很慢,会导致界面假死 这个我们可以自己写一个缓加载的TreeNode,让它继承于DefaultMutableTreeNode,在它里面定义加载标示,然后使用Swi

JTree使用

1 package JTree; 2 3 import java.awt.Component; 4 import javax.swing.Icon; 5 import javax.swing.JTree; 6 import javax.swing.tree.DefaultMutableTreeNode; 7 import javax.swing.tree.DefaultTreeCellRenderer; 8 9 10 public class IconNodeRenderer extends D

JTree用法及JTree使用经验总结&lt;转&gt;

JTree用法及JTree使用经验总结 import  java.awt.Dimension; import  java.awt.Color; import  javax.swing.JFrame; import  javax.swing.JPanel; import  javax.swing.JScrollPane; import  javax.swing.JTree; import  javax.swing.BoxLayout; import  javax.swing.tree.TreePa

Jtree (节点的渲染+资源管理器)

我们的还是自定义的Jtree的类: package jtree.customNode; import java.io.File; import javax.swing.JTree; import javax.swing.tree.DefaultTreeModel; import util.ImageManager; import jtree.checkBoxTree.CheckBoxTreeNodeListender; public class ZTreeCusNode extends JTre

java JTree 树形控件展示

package TreeView; import java.awt.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent; import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTree;import javax.swing.LookAndFeel;i