我正在开发一个应用程序,该应用程序将大量使用通过USB访问的外部存储器。我已经实现了用于浏览磁盘上目录的TreeModel。它适用于:
- Ubuntu上的本地光盘
- Ubuntu上连接的外部存储器
- Windows 7上的本地光盘
但在Windows7上连接外部存储器很糟糕,我不知道为什么。以pendrive作为根目录,用这个模型滚动JTree是非常麻烦的。一开始,我认为java.io.File中的listFiles()
对于pendrive来说速度较慢,所以我在模型中添加了一些缓存,但它不起作用——滚动仍然很糟糕。
我刚刚注意到它与Look&感觉对于系统L&对于Nimbus L&F它没有那么糟糕,但仍然不完美。
FileTreeModel:
import java.io.File;
import java.io.FileFilter;
import java.io.Serializable;
import java.util.*;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
public class FileTreeModel implements TreeModel {
private File root;
private boolean onlyFolders;
private boolean showHidden;
private final Object LEAF = new Serializable() {
};
private Map<File, Object> map;
private LinkedList<TreeModelListener> listeners = new LinkedList<>();
private FileFilter directoryFilter = new FileFilter() {
@Override
public boolean accept(java.io.File pathname) {
return pathname.isDirectory();
}
};
public FileTreeModel(File root, boolean onlyFolders, boolean showHidden) {
this.root = root;
this.onlyFolders = onlyFolders;
this.showHidden = showHidden;
this.map = new HashMap();
}
public FileTreeModel() {
}
public boolean isShowHidden() {
return showHidden;
}
public void setShowHidden(boolean showHidden) {
this.showHidden = showHidden;
}
@Override
public Object getRoot() {
return root;
}
public void setRoot(File root) {
Object oldRoot = this.root;
this.root = root;
map.clear();
TreeModelEvent event = new TreeModelEvent(root, new Object[]{root});
for (TreeModelListener listener : listeners) {
listener.treeStructureChanged(event);
}
}
@Override
public boolean isLeaf(Object node) {
return ((File) node).isFile();
}
@Override
public int getChildCount(Object parent) {
if (parent instanceof java.io.File && ((java.io.File) parent).canRead()) {
List<File> files = children(parent);
int result = 0;
for (java.io.File file : files) {
if (((file.isDirectory() && onlyFolders) || !onlyFolders)
&& ((!file.isHidden() && !showHidden) || showHidden)) {
result++;
}
}
return result;
}
return 0;
}
@Override
public Object getChild(Object parent, int index) {
if (parent instanceof java.io.File) {
List<File> files = children(parent);
List<java.io.File> resultFiles = new LinkedList<>();
for (java.io.File file : files) {
if (((file.isDirectory() && onlyFolders) || !onlyFolders)
&& ((!file.isHidden() && !showHidden) || showHidden)) {
resultFiles.add(file);
}
}
return resultFiles.get(index);
}
return null;
}
@Override
public int getIndexOfChild(Object parent, Object child) {
if (parent instanceof java.io.File) {
List<File> files = children(parent);
List<java.io.File> resultFiles = new LinkedList<>();
for (java.io.File file : files) {
if (((file.isDirectory() && onlyFolders) || !onlyFolders)
&& ((!file.isHidden() && !showHidden) || showHidden)) {
resultFiles.add(file);
}
}
return resultFiles.indexOf(child);
}
return -1;
}
@Override
public void valueForPathChanged(TreePath path, Object newvalue) {
}
@Override
public void addTreeModelListener(TreeModelListener l) {
listeners.add(l);
}
@Override
public void removeTreeModelListener(TreeModelListener l) {
listeners.remove(l);
}
//============================PRIVATE METHODS===============================
protected List<File> children(Object node) {
File f = (File) node;
Object value = map.get(f);
if (value == LEAF) {
return null;
}
List children = (List) value;
if (children == null) {
File[] c = f.listFiles();
if (c != null) {
children = new ArrayList(c.length);
for (int len = c.length, i = 0; i < len; i++) {
children.add(c[i]);
if (!c[i].isDirectory()) {
map.put(c[i], LEAF);
}
}
} else {
children = new ArrayList(0);
}
map.put(f, children);
}
return children;
}
}
样品形式:
import folderlist.model.treemodels.FileTreeModel;
import java.io.File;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jButton1.setText("Refresh");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTree1.setModel(new FileTreeModel());
jScrollPane1.setViewportView(jTree1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jComboBox1, 0, 173, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultComboBoxModel model = new DefaultComboBoxModel(getAvailableRoots());
jComboBox1.setModel(model);
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
File choosenRoot = (File) jComboBox1.getSelectedItem();
if (choosenRoot != null) {
FileTreeModel model = new FileTreeModel(choosenRoot, false, true);
jTree1.setModel(model);
}
}
public static void main(String args[]) {
try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
private Vector<File> getAvailableRoots() {
Vector<File> v = new Vector<File>(10, 1);
File userHome = new File(System.getProperty("user.home"));
if (userHome.isDirectory()) {
v.addElement(userHome);
}
File[] roots = File.listRoots();
for (File root : roots) {
v.addElement(root);
}
String os = System.getProperty("os.name").toLowerCase();
boolean isUnix = (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
if (isUnix) {
roots = new File("/media").listFiles();
for (File root : roots) {
v.addElement(root);
}
}
return v;
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTree jTree1;
// End of variables declaration
}
两个问题(我可以解决)是:
- 你没有缓存你的结果。文件列表是一项昂贵的操作,需要时间。在外部设备上更是如此。一旦你列出了一个目录,就要维护这个列表。如果你使用的是Java 7,你可以使用Fie Watcher服务,否则,你需要提供一个刷新选项
- 您应该将节点子级的加载卸载到后台任务中。看看http://www.jroller.com/Thierry/entry/swing_lazy_loading_in_a&http://www.jroller.com/Thierry/entry/swing_lazy_loading_in_jtree。虽然不完美,但尝试提供一个好主意
更新
当你看代码时,会发现有很多事情发生。对于单个节点,可能没有什么重要的,但当你开始获得几个节点时,延迟会开始变得明显。
因此,每当树需要重新绘制时,它都会通过调用getChildCount
、getChildren
和/或getChildAt
来遍历每个单独的节点。每一种方法本质上都在做同样的事情,一遍又一遍。
@Override
public int getChildCount(Object parent) {
if (parent instanceof java.io.File && ((java.io.File) parent).canRead()) {
List<File> files = children(parent);
int result = 0;
for (java.io.File file : files) {
if (((file.isDirectory() && onlyFolders) || !onlyFolders)
&& ((!file.isHidden() && !showHidden) || showHidden)) {
result++;
}
}
return result;
}
return 0;
}
@Override
public Object getChild(Object parent, int index) {
if (parent instanceof java.io.File) {
List<File> files = children(parent);
List<java.io.File> resultFiles = new LinkedList<>();
for (java.io.File file : files) {
if (((file.isDirectory() && onlyFolders) || !onlyFolders)
&& ((!file.isHidden() && !showHidden) || showHidden)) {
resultFiles.add(file);
}
}
return resultFiles.get(index);
}
return null;
}
最好有一个子模型,它包含所有文件的列表,然后基于属性(showHidden
和onlyFolders
)生成一个缓存的子模型,然后可以用来生成每个调用的结果。
例如
@Override
public int getChildCount(Object parent) {
int count = 0;
if (parent instanceof java.io.File && ((java.io.File) parent).canRead()) {
count = fileModel.getFilteredFiles().size();
}
return count;
}
这只是一个建议。
此外,根据最近的经验,File.canRead()
&File.canWrite()
可以在UAC处于活动状态的Windows 7计算机上返回误报:P