根据这个程序,我有以下几个问题1、我不需要从根目录展开Jtree,要从用户设定的路径(比如从“c:\windows”开始)展开,
我觉得这一句可能是有关路径的:
FileNode root=new FileNode(fileSystemView.getRoots()[0]);
但是,它的目录都不是字符串,我怎么自己设定啊?!
最大的问题就是这个例子里面,路径都不是字符串!!!2、它自定义了一个DetailTable,继承了JTable,我想实现双击表格的内容就可以打开文件(只打开txt文件),
 public void openSelect()
是在这里写吗?有相关的代码例子吗?或者告诉我用什么函数实现。3、我想在表格里面添加一个排序的功能,按时间,按类型之类的,如何实现?4、如何刷新左面的JTree?用UpdateUI?还是?

解决方案 »

  1.   

    源码
    ----------------------------------------------------------------------------
    public class WinExplorer extends JFrame implements TreeSelectionListener{
    JPanel contentPane=(JPanel)getContentPane();;
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu("文件");
    JMenuItem menuItemExit = new JMenuItem("退出");
    JToolBar toolBar = new JToolBar();
    JButton bttUp = new JButton();
    Icon iconUp=UIManager.getIcon("FileChooser.upFolderIcon");
    JLabel statusBar = new JLabel();//JTable的子类DetailTable,自己创建的=。=!
    DetailTable detailTable = new DetailTable();
    JScrollPane sp = new JScrollPane(detailTable);
    JSplitPane split = new JSplitPane();//这是干什么用的????
    FileSystemView fileSystemView=FileSystemView.getFileSystemView();//返回此系统的所有根分区。
    //例如,在 Windows 中,这将是“桌面”文件夹,而在 DOS 中将是从 A:到 Z:的驱动器。//这里是路径???!!!
    FileNode root=new FileNode(fileSystemView.getRoots()[0]);DefaultTreeModel treeModel=new DefaultTreeModel(root);
    JTree tree = new JTree(treeModel);public static void main(String argv[]){
        try {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          Font font=new Font("宋体",Font.PLAIN,12);
          String names[]={"Label","CheckBox","PopupMenu","TextPane",
                         "MenuItem","CheckBoxMenuItem","JRadioButtonMenuItem",
                         "ComboBox","Button","Tree","ScrollPane","TabbedPane",
                         "EditorPane","TitledBorder","Menu","TextArea","OptionPane",
                         "MenuBar","ToolBar","ToggleButton","ToolTip","ProgressBar",
                         "TableHeader","Panel","List","ColorChooser","PasswordField",
                         "TextField","Table","Label","Viewport","RadioButtonMenuItem",
                         "RadioButton"};
          for(int i=0;i<names.length;i++)UIManager.put(names[i]+".font",font);
          UIManager.put("Label.foreground",Color.black);
          UIManager.put("Border.foreground",Color.black);
          UIManager.put("TitledBorder.titleColor",Color.black);
          new WinExplorer().show();
       }catch(Exception e){
          e.printStackTrace();
       }
    }//构造函数
    public WinExplorer() {  //布局管理器  边界布局
      contentPane.setLayout(new BorderLayout());
      
      //窗口大小,居中
      Dimension dimension = getToolkit().getScreenSize();
      int i = (dimension.width - 640) / 2;
      int j = (dimension.height - 480) / 2;
      setBounds(i,j,640,480);
      setTitle("资源管理器");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setJMenuBar(menuBar);
      statusBar.setText(" ");  menuItemExit.addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e) {System.exit(0);}
      });  //设置“返回”按钮icon,以及动作
      bttUp.setIcon(iconUp);
      bttUp.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
          try{
              TreePath upPath=tree.getSelectionPath().getParentPath();
              if(upPath!=null){
                    tree.setSelectionPath(upPath);
                    tree.scrollPathToVisible(upPath);
              }
           }catch(Exception ex){}
        }
      });  //设置split窗口
      split.setDividerSize(6);
      split.setLeftComponent(new JScrollPane(tree));
      split.setRightComponent(sp);
      split.setDividerLocation(180);
      sp.getViewport().setBackground(Color.white);
     
      //设置并添加菜单栏、工具栏、状态栏等
      menuFile.add(menuItemExit);
      menuBar.add(menuFile);
      contentPane.add(toolBar, BorderLayout.NORTH);
      toolBar.add(bttUp, null);
      contentPane.add(statusBar, BorderLayout.SOUTH);
      contentPane.add(split, BorderLayout.CENTER);
      tree.addTreeExpansionListener(new MyExpandsionListener());
      //设置将用于绘制每个单元格的TreeCellRenderer
      tree.setCellRenderer(new MyTreeCellRenderer());  tree.addTreeSelectionListener(this);
      tree.setSelectionRow(0);  tree.setComponentOrientation(ComponentOrientation.UNKNOWN);
    }//值变化
    public void valueChanged(TreeSelectionEvent e){
       Object obj=tree.getLastSelectedPathComponent();
       if(obj==null)return;
       else detailTable.setParent(((FileNode)obj).getFile());
    }// MyTreeCellRenderer类,继承DefaultTreeCellRenderer
    class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      public MyTreeCellRenderer() {}
      public Component getTreeCellRendererComponent(JTree tree,Object value,
                boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus) {
          super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
          setIcon(fileSystemView.getSystemIcon(((FileNode)value).getFile()));
          return this;
      }
    }//树展开、折叠
    class MyExpandsionListener implements TreeExpansionListener {
      public MyExpandsionListener() {}
      public void treeExpanded(TreeExpansionEvent event) {
          if (tree.getLastSelectedPathComponent()==null){return;}
          tree.setCursor(new Cursor(Cursor.WAIT_CURSOR));
          TreePath path = event.getPath();
          FileNode node = (FileNode)path.getLastPathComponent();
          node.explore();
          treeModel.nodeStructureChanged(node);
          tree.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
      }
      public void treeCollapsed(TreeExpansionEvent event) {}
    }
      

  2.   

    //结点
    class FileNode extends DefaultMutableTreeNode {
        private boolean explored = false;
        public FileNode(File file)  { setUserObject(file); }
        public boolean getAllowsChildren() { return isDirectory(); }
        public boolean isLeaf()     { return !isDirectory();}
        public File getFile()        { return (File)getUserObject(); }
        public boolean isExplored() { return explored; }
        public void setExplored(boolean b){ explored=b;}
        public boolean isDirectory() { return getFile().isDirectory();}
        public String toString() {
            File file = (File)getUserObject();
            String filename = file.toString();
            int index = filename.lastIndexOf(File.separator);
            return (index != -1 && index != filename.length()-1)
                      ? filename.substring(index+1) : filename;
        }    //探索
        public void explore() {
            if(!isExplored()) {
                File file = getFile();
                File[] children = file.listFiles();
                if(children==null||children.length==0)return;
                for(int i=0; i < children.length; ++i)
                {
                     File f=children[i];
                     if(f.isDirectory())add(new FileNode(children[i]));
                }
                explored = true;
            }
       }
    }//表??????
    class DetailTable extends JTable{
          DetailTableModel model=new DetailTableModel();
          public DetailTable(){
              setModel(model);
              setShowGrid(false);
              TableColumnModel colModel = getColumnModel();
              for (int i=0;i<3;i++)
                colModel.getColumn(i).setCellRenderer(new DetailsTableCellRenderer());
              setRowHeight(18);
              this.addMouseListener(new MouseAdapter(){
                  public void mouseClicked(MouseEvent e) {
                      if(e.getClickCount()==2){
                         for (int i = 0; i <getRowCount(); i++) {
                              if(getCellRect(i,0,true).contains(e.getPoint())){
                                  openSelect();
                                  break;
                              }
                          }
                      }
                  }
              });
          }      public void openSelect(){
              Object obj=model.getValueAt(getSelectedRow(),0);
              if(obj==null)return;
              File f=(File)obj;
              if(f.isDirectory()){
                  //expand tree
              }else{
                  try{
              
                        }catch(Exception ee){}
                  //open select file
              }
          }
          public void setParent(File parent){
              model.removeAllRows();
              File list[]=parent.listFiles();
              if(list==null)return;
              Vector vDir=new Vector(),vFile=new Vector();
              for (int i = 0; i < list.length; i++) {
                  if(list[i].isDirectory())vDir.add(list[i]);
                  else vFile.add(list[i]);
              }
              sortElements(vFile);
              sortElements(vDir);
              for (int i = 0; i < vDir.size(); i++)model.addFile((File)vDir.elementAt(i));
              for (int i = 0; i < vFile.size(); i++)model.addFile((File)vFile.elementAt(i));
          }
          public void sortElements(Vector v)
           {
              for(int i=0;i<v.size();i++)
              {
                   int k=i;
                   for(int j=i+1;j<v.size();j++){
                       File fa=(File)v.elementAt(j);
                       File fb=(File)v.elementAt(k);
                       if(fileSystemView.getSystemDisplayName(fa).toLowerCase().compareTo(
                            fileSystemView.getSystemDisplayName(fb).toLowerCase())<0)k=j;
                   }
                   if(k!=i)swap(k,i,v);
              }
           }
           private void swap(int loc1,int loc2,Vector v){
               Object tmp=v.elementAt(loc1);
               v.setElementAt(v.elementAt(loc2),loc1);
               v.setElementAt(tmp,loc2);
           }
           //表模型
          class DetailTableModel extends DefaultTableModel {
              public DetailTableModel() {
                  addColumn("名称");
                  addColumn("大小");
                  addColumn("修改时间");
              }
              public void addFile(File f){
                  addRow(new Object[]{f,new Double(f.length()/1024),
                       new java.sql.Date(f.lastModified())});
              }
              public void removeAllRows(){
                  while(getRowCount()!=0) removeRow(0);
              }
              public boolean isCellEditable(int row, int column) {return false;}
          }      
          class DetailsTableCellRenderer extends DefaultTableCellRenderer {
            DetailsTableCellRenderer() {}
            public Component getTableCellRendererComponent(JTable table, Object value,
                                  boolean isSelected, boolean hasFocus, int row, int column) {
                if (column == 1){
                    setHorizontalAlignment(SwingConstants.TRAILING);
                    isSelected=hasFocus=false;
                }else if(column==2){
                    setHorizontalAlignment(SwingConstants.CENTER);
                    isSelected=hasFocus=false;
                }else setHorizontalAlignment(SwingConstants.LEADING);
                return super.getTableCellRendererComponent(
                            table, value, isSelected, hasFocus, row, column);
            }
            public void setValue(Object value) {
                setIcon(null);
                if (value instanceof File) {
                    File file = (File)value;
                    setText(fileSystemView.getSystemDisplayName(file));
                    setIcon(fileSystemView.getSystemIcon(file));
                }else{
                    super.setValue(value);
                }
            }
        }
      }
    }