请问各位大虾,我新建一个swing图片浏览管理器。
当我在右边的JList中新建一个文件夹,但是左边的树目录不更新。
代码如下:
/**
 * 新建文件夹
 */
jMenuItemNewdir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NewDirActionPerformed(evt);
}
});/**
 * <p>方法名:NewDirActionPerformed(java.awt.event.ActionEvent evt)</p>
 * <p>功能:新建文件夹</p>
 * <p>作者:William</p>
 * <p>编写日期:2009-8-27</p>
 * @param ActionEvent 监听事件类实例
 */
public void NewDirActionPerformed(java.awt.event.ActionEvent evt) {         //返回标识为定位的路径。 
TreePath path = jWDirTree1.getAnchorSelectionPath();
 //返回当前正在编辑的元素的路径。
 TreePath path1 = jWDirTree1.getEditingPath();
//返回首选节点的路径。
 TreePath path2 = jWDirTree1.getSelectionPath();
System.out.println("标识定位的路径"+path);
System.out.println("返回当前正在编辑的元素的路径"+path1);
System.out.println("返回首选节点的路径"+path2);
System.out.println("evt.getSource()"+evt.getSource());

// Object[] objs=path.getPath();
//返回此路径的最后一个组件。对于 DefaultTreeModel 返回的路径,它将返回一个 TreeNode 实例。 
JWTreeNode node = (JWTreeNode) path.getLastPathComponent();
String inputValue = JOptionPane.showInputDialog("新建文件夹名称");
  // 验证文件名是否合法
        if (!validateFileName(inputValue)) {
            JOptionPane.showMessageDialog(getParent(), "文件名不能包含下列任何字符之一  \\ / : * ? \" < > |");
            return;
        }

if (evt.getSource() instanceof JWDirTree) {
System.out.println("新建文件夹----------------:" + node);

final TreePath selectPath = ((JWDirTree) evt.getSource())
.getSelectionPath();
final JWTreeNode selectNode = (JWTreeNode) selectPath.getLastPathComponent();
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// pictureList.getNailListModel().ReloadList(selectNode);
// model.reload(selectNode);
// }
// }); }
String filePath = node.getFile().getAbsolutePath() + "\\"+ inputValue;
try {
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
this.getNailListModel().ReloadList(node);
} catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
this.getNailListModel().ReloadList(node);
// JWTreeNode rootNode = new JWTreeNode(rootFile);
// rootNode.toExplorer();
// this.jWDirTree1.setModel(new DefaultTreeModel(rootNode));
//  this.jWDirTree1.updateUI();
}

解决方案 »

  1.   


    还有代码:这个是JTree重写时间:public class JWTreeNode  extends DefaultMutableTreeNode implements  Serializable{   
        private boolean root = false;  //是否问根目录 
        private boolean isexplored = false;    //是否展现
        private boolean isleaf = false;  //是否是叶节点 
        /** Creates a new instance of JWTreeNode */   
        public JWTreeNode(final File nodeFile) {   
            setUserObject(nodeFile);   
        }   
          /**是否是文件夹
           * @return boolean
           */
        public boolean isDirectory() {   
            final File file = getFile();   
            return file.isDirectory();   
       }  
        /**
         * 是否为文件 同java.io.File.isFile()
         * @return
         */
        public boolean isFile(){
          File f=(File)super.getUserObject();
          return f.isFile();
        }
        /*   
         *   覆盖了DefaultMutableTreeNode.getAllowsChildren()方法。   
         *   如果FileNode代表的是目录,则允许有子节点。   
         */   
        public boolean getAllowsChildren() {      
                return isDirectory();               
        }   
       
       /**
        * 返回与此节点关联的 File 值。
        * 如果当前节点是File类型,那么就返回File
        * @return
        */
        public File getFile(){   
         //返回与此节点关联的 Object 值。
            final Object obj = getUserObject();   
            if (obj instanceof String){   
             //新建一个文件
                final File file = new File((File)((JWTreeNode)this.parent).getUserObject(),(String)obj);   
                  setUserObject(file);   
                }   
             return (File) getUserObject();   
        }   
        /**如果是文件返回文件名称,否则返回文件夹名称
         */
        @Override   
        public String toString() {   
            final File file = getFile();   
            if (file.getName().length()>0 )   
                return file.getName();   
            else  
             //将此抽象路径名转换为一个路径名字符串。所得到的字符串使用默认名称分隔符来分隔名称序列中的名称
                return file.getPath();                
        }   
           /**
            * 是否为根目录
            */
        @Override   
        public boolean isRoot(){   
            return this.root;           
        }   
        /*   
         *   覆盖了DefaultMutableTreeNode.isLeaf()方法。   
         *   如果FileNode代表的不是目录,那它就是一个叶子节点。   
         */   
        public boolean isLeaf(){   
            return this.isleaf;                      
        }   
        public boolean isExplored(){   
            return this.isexplored;   
        }   
        public void setRoot(final boolean root){   
            this.root = root;           
        }   
           //获得文件或者文件夹的大小
        public long getSize(){   
            long fsize = 0;   
            File file = getFile();  
            //如果文件不能读取,返回0
            if (!file.canRead())   
                return fsize;   
            //如果是文件夹返回文件夹的size
            if (!file.isDirectory())   
                return file.length();
            //获得文件夹下面的File List
            final File[] childrens = file.listFiles();   
            if (null != childrens){   
                for (final File Element:childrens)   
                    fsize = Element.length()+fsize;   
            }   
            return fsize;   
        }   
           /**
            * 打开非叶节点
            */
        public void toExplorer(){   
            if (isExplored())   
                return; 
            //是叶节点返回
            if (isLeaf() )   
                return;   
            final File file = getFile();   
        File[] files = null;
        //如果是根目录
            if (isRoot())   
                files =  JWUtility.getRoots();   
            else {   
                 files = file.listFiles();   
            }   
            if (files != null)   
                for (final File element : files){                 
                  if ( element.isDirectory() ){   
                      JWTreeNode  subNode = new JWTreeNode(element);   
                      subNode.isleaf = true;   
                      File[] subfiles = element.listFiles();     
                      if (subfiles != null)   
                      for (final File subElement:subfiles){   
                          if (subElement.isDirectory()){   
                              subNode.isleaf=false;   
                              break;   
                          }   
                      }                   
                      add( subNode );   
                  }   
                }   
            this.isexplored = true;                   
        }   
        /*   
         *   覆盖了DefaultMutableTreeNode.toString()方法。   
         *   返回路径的最后组件。   
         */   
       public   String   toString1()   
       {   
       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;   
       }   
         
      }  
      

  2.   

    这个是重写的JTREE树:   
    package imgexplorer.tree;   
       
    import java.awt.Color;   
    import javax.swing.JTree;   
    import javax.swing.SwingUtilities;   
    import javax.swing.event.TreeExpansionEvent;   
    import javax.swing.tree.DefaultTreeModel;   
    import javax.swing.tree.ExpandVetoException;   
    import javax.swing.tree.TreeModel;   
    import javax.swing.tree.TreePath;   
    import javax.swing.tree.TreeSelectionModel;   
    /**  
     *  树目录
     * @author wzh  
     */   
    public class JWDirTree extends JTree{   
        /**
     * 
     */
    private static final long serialVersionUID = 1L; /** Creates a new instance of JWDirTree */   
        public JWDirTree(){   
        }   
        // DefaultTreeModel 创建其中任何节点都可以有子节点的树。
        public JWDirTree(final DefaultTreeModel model) {   
            super(model);   
            //向此组件添加任意的键/值“客户端属性”。 
    //        key - 新的客户端属性键
    //        value - 新的客户端属性值,如果为 null,则此方法将移除该属性
    //        默认的,java风格会在节点间画出一个带直角的直线.通过设置Tree.lineStyle属性,
    //        你可以指定不同的样式.例如,如果采用java风格,通过调用如下代码,可以用横线来组织各节点.
            //putClientProperty("JTree.lineStyle", "Angled");   
            //putClientProperty("JTree.lineStyle", "Horizontal");   
            putClientProperty("JTree.lineStyle", "Angled");   
       
            final JWTreeRenderer renderer = new JWTreeRenderer();   
            setCellRenderer(renderer);   
            
            //addTreeExpansionListener(new JWTreeDiskExpansionAdapter());    
            addTreeWillExpandListener(new JWTreeDiskWillExpandAdapter());   
                  
            getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);   
            setBackground(Color.white);   
            //设置垂直对齐方式。
            setAlignmentX((float) 0.5);   
            setShowsRootHandles(false);   
            this.setDragEnabled(false);   
        }   
       
       /* @Override  
        public void setModel(TreeModel newModel) {  
           super.setModel(newModel);   
        }*/   
        /**
         * 当树扩展或折叠某一节点时获得通知的侦听器。
         */
        final class JWTreeDiskWillExpandAdapter implements javax.swing.event.TreeWillExpandListener {   
       
            public final void treeWillExpand(final TreeExpansionEvent e) throws ExpandVetoException {   
                final TreePath path = e.getPath();   
       
                final JWTreeNode selectedNode = (JWTreeNode) path.getLastPathComponent();   
       
                if (!selectedNode.isExplored())   
                    selectedNode.toExplorer();   
            }   
       
            public final void treeWillCollapse(final TreeExpansionEvent e) {   
            }   
        }   
       
       /* final class JWTreeDiskExpansionAdapter implements javax.swing.event.TreeExpansionListener {  
      
            public final void treeExpanded(final TreeExpansionEvent e) {  
                final Thread runner = new Thread() {  
                    @Override  
                    public void run() {  
                        Runnable runnable = new Runnable() {  
                            public void run() {  
                                TreePath path = JWDirTree.this.getSelectionPath();  
                                if (path != null)  
                                    JWDirTree.this.setSelectionPath(path);                           
                            }  
                        };  
                        SwingUtilities.invokeLater(runnable);  
                    }  
                };  
                runner.start();  
            }  
      
            public final void treeCollapsed(final TreeExpansionEvent e) {  
            }  
        }*/   
    }           
      

  3.   

    新建JList内文件夹的时候,更新JTree的TreeModel,界面没更新就对JTree进行一次updateUI()
      

  4.   

    CSDN是不是有问题了?这么古董的帖子怎么能让我在首页看到?更奇怪的是下面还有很多6,7月份的帖子-_-!
      

  5.   

    请问diggywang:对Model的更新是否安全,可以放在普通线程么?
      

  6.   

    对任何Swing组件及其model的更新都是线程不安全的,除非你确定做model更新的时候不会有其它线程去改变它,那放在普通线程没问题。一般此类操作都需要在EDT线程中执行,对超长时间的处理,建议使用SwingWorker
      

  7.   

    顶diggywang
    同意用SwingWorker