日期:2014-05-20  浏览次数:20760 次

java Swing 右边新建目录,左边JTree目录刷新?
请问各位大虾,我新建一个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();


}

------解决方案--------------------
新建JList内文件夹的时候,更新JTree的TreeModel,界面没更新就对JTree进行一次updateUI()
------解决方案--------------------
请问diggywang:

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


同意用SwingWorker