JAVA编程,用JTree浏览D盘中的*.txt文件
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileFilter;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.MessageFormat;
/**
* @author Hardneedl
*/
class JavaExplorer extends JFrame {
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(600, 400);
private JLabel statusLabel;
private JTree tree;
private JTable detailTable;
private FileTableModel tableModel;
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "Java Explorer";}
JavaExplorer() throws HeadlessException {
init();
doLay();
attachListeners();
}
private void init() {
statusLabel = new JLabel(){public Color getForeground() {return Color.BLUE;}};
tree = new JTree(new FileTreeModel());
tree.setCellRenderer(new DirCellRenderer());
detailTable = new JTable(tableModel = new FileTableModel());
detailTable.getColumnModel().getColumn(2).setCellRenderer(new TableCellRenderer(){
private JLabel label=new JLabel();
private final SimpleDateFormat format = new SimpleDateFormat("yyyy年mm月dd日 HH时MM分ss秒");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Calendar){
Calendar cal = (Calendar)value;
label.setText( format.format(cal.getTime()) );
}
return label;
}
});
detailTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer(){
private JLabel label = new JLabel();
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof File) {
File f = (File)value;
label.setText(f.getName());
label.setForeground( f.isDirectory()? Color.RED : Color.BLACK);
}
return label;
}
});
}
private void doLay() {
Container container = getContentPane();
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), new JScrollPane(detailTable));
container.add(splitPane,BorderLayout.CENTER);
container.add(statusLabel,BorderLayout.SOUTH);
pack();
}
private void attachListeners() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tree.addTreeSelectionListener(new SelectionListener());
tree.addTreeSelectionListener(new _DirSelectionListener());
}
public static void main(String[] args) {
new JavaExplorer().setVisible(true);
}
private class FileTreeModel implements TreeModel {
private File[] rootFiles;
private final FileFilter dirFilter = new FileFilter(){
public boolean accept(File f) {return f.isDirectory();}
};
private FileTreeModel() {rootFiles = File.listRoots();}
public Object getRoot() {return "我的电脑";}
public Object getChild(Object parent, int index) {
if (parent==getRoot()) return rootFiles[index];
if (parent instanceof File) {
File pf = (File)parent;
return pf.listFiles(dirFilter)[index];
}
return null;
}
public int getChildCount(Object parent) {
if (parent == getRoot()) return rootFiles.length;
if (parent instanceof File){
File pf = (File)parent;
File[] fs = pf.listFiles(dirFilter);
return fs == null?0:fs.length;
}
return 0;
}
public boolean isLeaf(Object node) {return false;}
public void valueForPathChanged(TreePath path, Object newValue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
public int getIndexOfChild(Object parent, Object child) {
if (parent == getRoot()) {
for (int i = 0,j=rootFiles.length; i < j; i++)
if (rootFiles[i]==child) return i;
}
if (parent instanceof File) {
File pf = (File)parent;
File[] fs = pf.listFiles(dirFilter);
for (int i = 0,j=fs.length; i < j; i++) {
if (fs[i].equals(child)) return i;
}
}
return -1;
}
}
private class FileTableModel extends AbstractTableModel {
public int getRowCount() {return dir==null||dir.isFile()?0:dir.listFiles().length;}
public int getColumnCount() {return 3;}
private File dir;
private void setDir(File dir){
this.dir = dir;
fireTableDataChanged();
}
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:return File.class;
case 1:return Integer.class;
case 2:return Calendar.class;
default:return String.class;
}
}
public String getColumnName(int column) {
switch (column) {
case 0: return "名称";
case 1: return "大小";
case 2: return "修改日期";
default:return "";
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
File[]fs=dir.listFiles();
File f = fs[rowIndex];
switch(columnIndex){
case 0:return f;
case 1:
if (f.isDirectory()) return null;
try {
if (f.canRead())
return new FileInputStream(f).available();
} catch (IOException e) {
e.printStackTrace();
}
case 2:
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(f.lastModified());
return cl;
}
return null;
}
}
private class _DirSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getNewLeadSelectionPath();
if (path!=null){
Object obj = path.getLastPathComponent();
if (obj instanceof File) {
File f = (File)obj;
File[] fs = f.listFiles();
statusLabel.setText(fs==null?null:MessageFormat.format("{0}个文件",fs.length ));
}
else
statusLabel.setText(null);
}
}
}
private class DirCellRenderer extends JLabel implements TreeCellRenderer {
public boolean isOpaque() {return true;}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof File){
String s = ((File)value).getName();
setText(s.isEmpty()?value.toString() : s);
}
else
setText(value.toString());
setForeground(selected? Color.BLUE : Color.BLACK);
setBackground(selected? Color.YELLOW : Color.WHITE);
return this;
}
}
private class SelectionListener implements TreeSelectionListener{
public void valueChanged(TreeSelectionEvent e) {
Object obj = e.getNewLeadSelectionPath().getLastPathComponent();
if (obj instanceof File) {
tableModel.setDir((File)obj);
}
}
}
}