RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:30-18:00
你可能遇到了下面的问题
关闭右侧工具栏
JTree实现的系统文件目录树
  • 作者:zhaozj
  • 发表时间:2020-12-23 10:52
  • 来源:未知

看到很多人问关于用JTree实现资源管理器的方法,在这里我提供一个例子共大家参考,这个例子虽然也是转自其他书,但是JTree的用法,我掌握的差不多了,如果哪位朋友,对此例子有问题,我愿意与他交流。我的email是:jack_kui@126.com这个例子涵盖了JTree的大部分属性,希望对大家能够有所帮助。需要一些图标文件,请大家自己复制好相同名字的gif图片放到目录下。

下面是源代码:

import java.awt.*;import java.awt.event.*;import java.io.*;import java.util.*;

import javax.swing.*;import javax.swing.tree.*;import javax.swing.event.*;

public class FileTree1  extends JFrame { public static final ImageIcon ICON_COMPUTER =   new ImageIcon("computer.gif"); public static final ImageIcon ICON_DISK =   new ImageIcon("disk.gif"); public static final ImageIcon ICON_FOLDER =   new ImageIcon("folder.gif"); public static final ImageIcon ICON_EXPANDEDFOLDER =   new ImageIcon("expandedfolder.gif");

 protected JTree  m_tree; protected DefaultTreeModel m_model; protected JTextField m_display;

 public FileTree1() {  super("Directories Tree");  setSize(400, 300);

  DefaultMutableTreeNode top = new DefaultMutableTreeNode(   new IconData(ICON_COMPUTER, null, "Computer"));

  DefaultMutableTreeNode node;  File[] roots = File.listRoots();  for (int k=0; k<roots.length; k++)  {   node = new DefaultMutableTreeNode(new IconData(ICON_DISK,     null, new FileNode(roots[k])));   top.add(node);                        node.add( new DefaultMutableTreeNode(new Boolean(true)));  }

  m_model = new DefaultTreeModel(top);  m_tree = new JTree(m_model);

                m_tree.putClientProperty("JTree.lineStyle", "Angled");

  TreeCellRenderer renderer = new    IconCellRenderer();  m_tree.setCellRenderer(renderer);

  m_tree.addTreeExpansionListener(new    DirExpansionListener());

  m_tree.addTreeSelectionListener(new    DirSelectionListener());

  m_tree.getSelectionModel().setSelectionMode(   TreeSelectionModel.SINGLE_TREE_SELECTION);   m_tree.setShowsRootHandles(true);   m_tree.setEditable(false);

  JScrollPane s = new JScrollPane();  s.getViewport().add(m_tree);  getContentPane().add(s, BorderLayout.CENTER);

  m_display = new JTextField();  m_display.setEditable(false);  getContentPane().add(m_display, BorderLayout.NORTH);

  WindowListener wndCloser = new WindowAdapter()  {   public void windowClosing(WindowEvent e)    {    System.exit(0);   }  };  addWindowListener(wndCloser);    setVisible(true); }

 DefaultMutableTreeNode getTreeNode(TreePath path) {  return (DefaultMutableTreeNode)(path.getLastPathComponent()); }