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-12-20 13:15:32

JTree的相关文章

使用jdom操作xml数据,生成含Jtree的applet

dom|xml|数据 转自:http://www.softhouse.com.cn/html/200410/2004102517145700001335.html 使用jdom操作xml数据,生成含Jtree的applet    在我们工作中,常常会碰到树形组件的生成问题,如果你在开发web application,纯粹使用javascript来生成树形组件是非常繁琐的,而且交互性也不不太好.所以许多产品使applet来实现树形组件的功能.比如说,weblogic,jboss等产品的consol

JTree demo

  JFrame居中方法一:   setLocationRelativeTo(null);  注意:必须在整个frame初始化完成后再加上此语句,否则将显示在屏幕右下角 方法二: private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();   /** 屏幕宽度 */  private int screenWidth = screenSize.width;   /** 屏幕高度 */  private in

java-Java swing怎么向JcomBox 下拉列表框里添加Jtree组件?

问题描述 Java swing怎么向JcomBox 下拉列表框里添加Jtree组件? 在Jcombox里需要用到一个带选择框的Jtree组件,该怎么来实现?求大神解救. 解决方案 要想在下拉列表中显示树型结构,只能转变思路,这是由底层决定的.

[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

关于SWING JTREE 的焦点问题

问题描述 做了一个带标题的组件,该组件由一个标题面板,一个内容面板,这个内容面板可以放置任何其它组件,这里放了一个JTree现在我想在标题面板被选中时,内容面板中的JTree自动选中到上一次选择的节点.其实就是想做一个类似IntelliJIDEA的视图组件.如下图图1.这是选中时的样子图2.这是没有选中的样子现在的问题是:1.当我选择了JTree中的某一节点时,不知道怎么通知标题面板改变样式2.当我选择了标题面板时,不知道怎么让JTree中高亮(如图1中的样子) 解决方案 解决方案二:记录一下上

label-&amp;amp;lt;Jtree&amp;amp;gt;,JPanel中添加JLabel显示问题

问题描述 <Jtree>,JPanel中添加JLabel显示问题 public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { java.awt.Component component = null; if(selected) { Defa

java swing中一个JTree如何在多个panel中显示

问题描述 java swing中一个JTree如何在多个panel中显示 要实现的功能是 需要在2个panel(A, B )中显示用户组的树结构, 其中有一个panel(B)中提供了对树的增删改,运行程序首先显示A, 通过A上的按钮点击事件显示B, 要在B更改同时更新A上的显示情况, 现在遇到的情况是:当点击A上的按钮显示B时,A上的tree就不见了: 怎么解决啊? A的部分代码 DefaultMutableTreeNode root = new DefaultMutableTreeNode("

关于jtree节点的展开

问题描述 在写一个jtree时想在treeExpanded事件中得到被展开的那个节点有什么方法啊,新手求助,谢谢了 解决方案 解决方案二:......急于求答谢谢了解决方案三:publicvoidtreeExpanded(TreeExpansionEventevent){DefaultMutableTreeNodenode=(DefaultMutableTreeNode)jTree.getSelectionPath().getLastPathComponent();System.out.prin

请问从一个JFrame中如何控制另一个JFrame中的JTree啊?

问题描述 求教:我在一个JFrame(称为A)中向数据库写数据,然后在A中调用另一个JFrame(称为B)中的JTree重新从数据库中读取数据建立结点树.数据成功写入数据库,调试也显示JTree能够从数据库中读取新数据并建立DefaultTreeModel,但JTree不能根据新的数据显示结点树.请教各位怎样让JTree显示新的结点树啊? 解决方案 解决方案二:JFrame窗体也是类对象啊,你在类里定义一个方法,做自己需要做的事情,根据窗体对象的引用访问方法不就可以了.解决方案三:你只要发送事件