import javax.swing.*; import javax.swing.table.*; import java.awt.*; import java.io.*; import java.util.*; // // A simple JTable example which displays // file names and sizes for all files in a // directory, plus indicates whether an entry // is a directory itself or not. // // Currently this is all read-only, add listeners // to implement whatever actions ... // public class FileTable extends JPanel { public FileTable(File top) { super(new GridLayout(1,0)); JTable table = new JTable(new MyTableModel(top)); table.setPreferredScrollableViewportSize(new Dimension(500, 500)); table.setAutoCreateRowSorter(true); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); } class FileEntry { private String fname; private long fsize; private boolean isfile; public FileEntry(String name, long size, boolean file) { fname = name; fsize = size; isfile = file; } public Object getCol(int col) { switch (col) { case 0: return fname; case 1: return fsize; case 2: return isfile; } return null; } } class MyTableModel extends AbstractTableModel { private ArrayList data = new ArrayList(); MyTableModel(File top) { addFiles(top); } public void addFiles(File d) { File[] allfiles = d.listFiles(); for (File f : allfiles) { data.add(new FileEntry(f.toString(),f.length(),f.isFile())); if (f.isDirectory()) addFiles(f); } } private String[] columnNames = {"Filename", "Size", "File"}; public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.size(); } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data.get(row).getCol(col); } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } } private static void createAndShowGUI(File top) { JFrame frame = new JFrame("TableDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); FileTable newContentPane = new FileTable(top); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { if (args.length != 1) { System.out.println("Must supply one filename only"); System.exit(1); } final File top = new File(args[0]); if (!top.isDirectory()) { System.out.println("You didn't specify a directory"); System.exit(1); } javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(top); } }); } }