extends AbstractTableModel (Custom class type) : AbstractTableModel « javax.swing.table « Java by API






extends AbstractTableModel (Custom class type)

import java.awt.BorderLayout;
import java.io.File;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class MainClass extends JFrame {

  public MainClass() {
    super("Custom TableModel Test");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    FileModel fm = new FileModel();
    JTable jt = new JTable(fm);
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    jt.setColumnSelectionAllowed(true);

    JScrollPane jsp = new JScrollPane(jt);
    getContentPane().add(jsp, BorderLayout.CENTER);
  }

  public static void main(String args[]) {
    MainClass ft = new MainClass();
    ft.setVisible(true);
  }
}

class FileModel extends AbstractTableModel {

  String titles[] = new String[] { "Directory?", "File Name", "Read?", "Write?", "Size",
      "Last Modified" };

  Class types[] = new Class[] { Boolean.class, String.class, Boolean.class, Boolean.class,
      Number.class, Date.class };

  Object data[][];

  public FileModel() {
    this(".");
  }

  public FileModel(String dir) {
    File pwd = new File(dir);
    setFileStats(pwd);
  }

  public int getRowCount() {
    return data.length;
  }

  public int getColumnCount() {
    return titles.length;
  }

  public String getColumnName(int c) {
    return titles[c];
  }

  public Class getColumnClass(int c) {
    return types[c];
  }

  public Object getValueAt(int r, int c) {
    return data[r][c];
  }

  public void setFileStats(File dir) {
    String files[] = dir.list();
    data = new Object[files.length][titles.length];

    for (int i = 0; i < files.length; i++) {
      File tmp = new File(files[i]);
      data[i][0] = new Boolean(tmp.isDirectory());
      data[i][1] = tmp.getName();
      data[i][2] = new Boolean(tmp.canRead());
      data[i][3] = new Boolean(tmp.canWrite());
      data[i][4] = new Long(tmp.length());
      data[i][5] = new Date(tmp.lastModified());
    }

    fireTableDataChanged();
  }
}

           
       








Related examples in the same category

1.extends AbstractTableModel (read database table to a JTable)
2.extends AbstractTableModel
3.AbstractTableModel: fireTableRowsUpdated(int firstRow, int lastRow)