Results 1 to 3 of 3
- 08-07-2007, 04:03 AM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
Help with application with JTable
Hi, I currently have a Jtable, allows only 1 row selection at a time, it is used for listing the files in a certain directory.
This will get all the files from the certain directory to populate the JTable,
What I need to do now is extension type filter, sort by the type and the size, not include any sub-directory ONLY files
Also I wanted to know if there is any way to sync. the table in real-time,Java Code:public Object[][] getFileStats(File dir) { String files[] = dir.list(); Object[][] results = new Object[files.length][titles.length]; int j=0; // this is to remove folders from the table for (int i = 0; i < files.length; i++) { File tmp = new File(files); boolean isDir = tmp.isDirectory(); if (isDir) { // dir is a directory j++; } else { // dir is a file // NEED TO FILTER BY THE FILE EXTENTION, FOR EXAMPLE ONLY *.txt,*.jpg // ???? results[i-j][0] = tmp.getName(); results[i-j][1] = new Long(tmp.length()); results[i-j][2] = new Date(tmp.lastModified()); // THE BOTTOM ROWS ARE ALL BLANK NOW, BECAUSE OF THE FOLDERS, HOW DO I REMOVE THEM FROM THE "results" ARRAY ?? } } return results; } ////////////////// // create JTable and add the content into it // ......... table2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (ALLOW_ROW_SELECTION) { // true by default ListSelectionModel rowSM = table2.getSelectionModel(); rowSM.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { //Ignore extra messages. if (e.getValueIsAdjusting()) return; ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (lsm.isSelectionEmpty()) { System.out.println("No rows are selected."); } else { selectedRow = lsm.getMinSelectionIndex(); System.out.println("Row " + selectedRow + " is now selected."); javax.swing.table.TableModel model = table2.getModel(); System.out.print(" " + model.getValueAt(selectedRow, 0)); // NEED TO VERIFY IF FILE EXISTS File f10 = new File((String)model.getValueAt(selectedRow, 0)); System.out.println(f10.exists() ? "exists" : "does not exist"); // IF NOT EXIST, REMOVE ROW // if (f10.exists()){ System.out.println(" "); } else {model.removeRow(selectedRow); } //// ERROR ????? } } }); }
for example, if a new file is created, then it will automatically be added to the table, or a file is renamed, so the old file will not exist so the row is deleted but a row row is created with the new filename ??
Thanks.
- 08-07-2007, 07:57 AM #2
Member
- Join Date
- Jul 2007
- Posts
- 35
- Rep Power
- 0
Also I wanted to know if there is any way to sync. the table in real-time,} else {
// To modify the model it must be a DefaultTableModel or
// one you build yourself. The TableModel interface does
// not have a removeRow method.
model.removeRow(selectedRow); //// ERROR ?????
}
for example, if a new file is created, then it will automatically be added to the table, or a file is renamed, so the old file will not exist so the row is deleted but a row row is created with the new filename ??
Yes. These changes will take place in an event listener of some kind or you need to make arrangements to listen for the changes that are to be made for/to your table data. In the code for or called by this listener:
1 - get a reference to the DefaultTableModel for the table
2 - add, change the column values of or remove the desired row
3 - using the addRow or removeRow methods will generate the notices to listeners needed to update the model. If the data was changed tell the model with fireTableCellUpdate, an AbstractTableModel (super)class method. The JTable listens to its model which tells the table to update itself so you only need to make changes to the model.
Java Code:import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.*; import java.util.Date; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class FileTable implements ListSelectionListener { JTable table; public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int row = table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel)table.getModel(); System.out.println("valueAt(" + row + ", 0) = " + model.getValueAt(row, 0)); } } private JScrollPane getContent() { File dir = new File("."); dir.setReadOnly(); Object[][] data = getFileData(dir); Object[] colIds = { "Name", "Size", "Last Modified" }; DefaultTableModel model = new DefaultTableModel(data, colIds); table = new JTable(model) { public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; table.setDefaultRenderer(Date.class, new DateRenderer()); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); ListSelectionModel rowSM = table.getSelectionModel(); rowSM.addListSelectionListener(this); return new JScrollPane(table); } private Object[][] getFileData(File dir) { File[] files = dir.listFiles(javaFilter); int fileCount = getFileCount(files); int columns = 3; Object[][] results = new Object[fileCount][columns]; for (int j = 0; j < files.length; j++) { results[j][0] = files[j].getName(); results[j][1] = new Long(files[j].length()); results[j][2] = new Date(files[j].lastModified()); } return results; } private int getFileCount(File[] files) { int count = 0; for(int j = 0; j < files.length; j++) { if(files[j].isFile()) count++; } System.out.println("count = " + count); return count; } private String getExtension(File file) { String s = file.getPath(); int dot = s.lastIndexOf("."); return s.substring(dot+1); } private FileFilter javaFilter = new FileFilter() { String JAVA = "java"; public boolean accept(File file) { return getExtension(file).equalsIgnoreCase(JAVA); } }; private class DateRenderer extends DefaultTableCellRenderer.UIResource { DateFormat formatter = new SimpleDateFormat("HHmm ddMMMyyyy"); public DateRenderer() { super(); } public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } } public static void main(String[] args) { FileTable test = new FileTable(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(test.getContent()); f.pack(); f.setLocation(200,200); f.setVisible(true); } }
- 08-08-2007, 08:51 AM #3
Java Code:import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.table.*; public class TableSorting { JTable table; DateFormat df = new SimpleDateFormat("HHmm ddMMMyyyy"); String filePath = "."; private JScrollPane getTableComponent() { table = new JTable(new CustomTableModel(0,3)); loadTable(TableFilter.ALL); TableColumnModel colModel = table.getColumnModel(); colModel.getColumn(0).setPreferredWidth(250); colModel.getColumn(1).setPreferredWidth(75); colModel.getColumn(2).setPreferredWidth(150); table.setAutoCreateColumnsFromModel(false); return new JScrollPane(table); } private void loadTable(int id) { TableFilter filter = new TableFilter(id); CustomTableModel model = (CustomTableModel)table.getModel(); File folder = new File(filePath); File[] files = folder.listFiles(filter); String[][] data = new String[files.length][model.getColumnCount()]; for(int j = 0; j < files.length; j++) { File file = files[j]; data[j][0] = files[j].getName(); data[j][1] = getSize(files[j]); data[j][2] = df.format(files[j].lastModified()); } model.setDataVector(data, model.colIds); } private String getSize(File file) { // Directories not allowed. long size = file.length(); int count = 0; while(size > 1024) { size >>= 10; count++; } switch(count) { case 0: return "1KB"; case 1: return String.valueOf(size) + "KB"; default: return String.valueOf(size) + "MB"; } } private void sortBySize() { CustomTableModel model = (CustomTableModel)table.getModel(); Vector rows = model.getDataVector(); Collections.sort(rows, sizeSorter); model.fireTableStructureChanged(); } private Comparator sizeSorter = new Comparator() { public int compare(Object a, Object b) { String s1 = ((Vector)a).get(1).toString(); String s2 = ((Vector)b).get(1).toString(); int n1 = Integer.parseInt(s1.substring(0, s1.length()-2)); int n2 = Integer.parseInt(s2.substring(0, s2.length()-2)); if(n1 < n2) return -1; if(n1 > n2) return 1; return 0; } }; private void sort() { CustomTableModel model = (CustomTableModel)table.getModel(); Vector rows = model.getDataVector(); Collections.sort(rows, sorter); model.fireTableStructureChanged(); } private Comparator sorter = new Comparator() { public int compare(Object a, Object b) { String s1 = ((Vector)a).get(0).toString().toLowerCase(); String s2 = ((Vector)b).get(0).toString().toLowerCase(); return s1.compareTo(s2); } }; private JPanel getUIPanel() { String[] ids = { "all", "java", "txt" }; ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { String ac = e.getActionCommand(); if(ac.equals("SIZE")) { if(((JCheckBox)e.getSource()).isSelected()) sortBySize(); else sort(); } else { int filterID = -1; if(ac.equals("ALL")) filterID = TableFilter.ALL; else if(ac.equals("JAVA")) filterID = TableFilter.JAVA; else if(ac.equals("TXT")) filterID = TableFilter.TXT; loadTable(filterID); } } }; ButtonGroup group = new ButtonGroup(); JPanel panel = new JPanel(); for(int j = 0; j < ids.length; j++) { JRadioButton rb = new JRadioButton(ids[j], j==0); rb.setActionCommand(ids[j].toUpperCase()); rb.addActionListener(al); group.add(rb); panel.add(rb); } JCheckBox cb = new JCheckBox("size", false); cb.setActionCommand("size".toUpperCase()); cb.addActionListener(al); panel.add(cb); return panel; } public static void main(String[] args) { TableSorting test = new TableSorting(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(test.getTableComponent()); f.getContentPane().add(test.getUIPanel(), "Last"); f.setSize(500,400); f.setLocation(200,200); f.setVisible(true); } } class CustomTableModel extends DefaultTableModel { String[] colIds = { "name", "size", "last modified" }; public CustomTableModel(int rows, int columns) { super(rows, columns); } public String getColumnName(int column) { return colIds[column]; } } class TableFilter implements FileFilter { final static int ALL = 0; final static int JAVA = 1; final static int TXT = 2; int id = 0; public TableFilter(int id) { this.id = id; } public boolean accept(File file) { if(file.isDirectory()) return false; String ext = getExtension(file); boolean accept = false; switch(id) { case ALL: accept = true; break; case JAVA: accept = "java".equals(ext); break; case TXT: accept = "txt".equals(ext); break; default: System.out.println("Unexpected TableFilter id: " + id); } return accept; } private String getExtension(File file) { String s = file.getPath(); int dot = s.lastIndexOf("."); if(dot != -1 && dot < s.length()) return s.substring(dot+1); return null; } }
Similar Threads
-
Display XML in JTable
By boy22 in forum XMLReplies: 2Last Post: 12-07-2008, 06:03 PM -
Launching an application from another application dynamically
By Java Tip in forum Java TipReplies: 0Last Post: 02-16-2008, 09:31 PM -
Launching an application from another application using thread
By Java Tip in forum Java TipReplies: 0Last Post: 02-16-2008, 09:29 PM -
How to add in a new row in Jtable?
By Ry4n in forum AWT / SwingReplies: 0Last Post: 01-18-2008, 12:26 PM -
Help with JTable
By fernando in forum AWT / SwingReplies: 1Last Post: 08-07-2007, 06:57 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks