Java by API/javax.swing.table/AbstractTableModel

Материал из Java эксперт
Перейти к: навигация, поиск

AbstractTableModel: fireTableRowsUpdated(int firstRow, int lastRow)

import java.awt.BorderLayout;
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("Dynamic Data Test");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JTable jt = new JTable(new MarketDataModel(5));
    JScrollPane jsp = new JScrollPane(jt);
    getContentPane().add(jsp, BorderLayout.CENTER);
  }
  public static void main(String args[]) {
    MainClass mt = new MainClass();
    mt.setVisible(true);
  }
}
class MarketDataModel extends AbstractTableModel implements Runnable {
  Thread runner;
  public MarketDataModel(int initialDelay) {
    Thread runner = new Thread(this);
    runner.start();
  }
  double[] data = new double[]{1,2,3,4,5};
  
  String[] headers = { "Symbol", "Price", "Change", "Last updated" };
  public int getRowCount() {
    return 1;
  }
  public int getColumnCount() {
    return headers.length;
  }
  public String getColumnName(int c) {
    return headers[c];
  }
  public Object getValueAt(int r, int c) {
    return data[c];
  }

  public void updateStocks() {
    for (int i = 0; i < data.length; i++) {
      data[i] = Math.random();
    }
  }
  public void run() {
    while (true) {
      updateStocks();
      fireTableRowsUpdated(0, data.length - 1);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {
      }
    }
  }
}





extends AbstractTableModel

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class MainClass {
  public static void main(final String args[]) {
    final Object rows[][] = { { "one", "1" }, { "two", "2" },
        { "three", "3" } };
    final String headers[] = { "English", "Digit" };
    
    TableModel fixedColumnModel = new AbstractTableModel() {
      public int getColumnCount() {
        return 2;
      }
      public String getColumnName(int column) {
        return headers[column];
      }
      public int getRowCount() {
        return 3;
      }
      public Object getValueAt(int row, int column) {
        return rows[row][column];
      }
    };
    
    
    
    JFrame frame = new JFrame("Scrollless Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTable table = new JTable(fixedColumnModel);
    
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    
    frame.add(new JScrollPane(table), BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





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();
  }
}





extends AbstractTableModel (read database table to a JTable)

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
public class MainClass extends JFrame {
  JTextField hostField;
  JTextField queryField;
  QueryTableModel qtm = new QueryTableModel();
  public MainClass() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(350, 200);
    JTable table = new JTable(qtm);
    JScrollPane scrollpane = new JScrollPane(table);
    JPanel commandPanel = new JPanel();
    commandPanel.setLayout(new GridLayout(3, 2));
    commandPanel.add(new JLabel("Enter the Host URL: "));
    commandPanel.add(hostField = new JTextField());
    commandPanel.add(new JLabel("Enter your query: "));
    commandPanel.add(queryField = new JTextField());
    commandPanel.add(new JLabel("Click here to send: "));
    JButton jb = new JButton("Search");
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        qtm.setHostURL(hostField.getText().trim());
        qtm.setQuery(queryField.getText().trim());
      }
    });
    commandPanel.add(jb);
    getContentPane().add(commandPanel, BorderLayout.NORTH);
    getContentPane().add(scrollpane, BorderLayout.CENTER);
  }
  public static void main(String args[]) {
    MainClass tt = new MainClass();
    tt.setVisible(true);
  }
}
class QueryTableModel extends AbstractTableModel {
  Vector cache;
  int colCount;
  String[] headers;
  Connection db;
  Statement statement;
  String currentURL;
  public QueryTableModel() {
    cache = new Vector();
  }
  public String getColumnName(int i) {
    return headers[i];
  }
  public int getColumnCount() {
    return colCount;
  }
  public int getRowCount() {
    return cache.size();
  }
  public Object getValueAt(int row, int col) {
    return ((String[]) cache.elementAt(row))[col];
  }
  public void setHostURL(String url) {
    if (url.equals(currentURL)) {
      return;
    }
    closeDB();
    initDB(url);
    currentURL = url;
  }
  public void setQuery(String q) {
    cache = new Vector();
    try {
      ResultSet rs = statement.executeQuery(q);
      ResultSetMetaData meta = rs.getMetaData();
      colCount = meta.getColumnCount();
      headers = new String[colCount];
      for (int h = 1; h <= colCount; h++) {
        headers[h - 1] = meta.getColumnName(h);
      }
      while (rs.next()) {
        String[] record = new String[colCount];
        for (int i = 0; i < colCount; i++) {
          record[i] = rs.getString(i + 1);
        }
        cache.addElement(record);
      }
      fireTableChanged(null);
    } catch (Exception e) {
      cache = new Vector();
      e.printStackTrace();
    }
  }
  public void initDB(String url) {
    try {
      Class.forName("your driver class");
      db = DriverManager.getConnection(url);
      statement = db.createStatement();
    } catch (Exception e) {
      System.out.println("Could not initialize the database.");
      e.printStackTrace();
    }
  }
  public void closeDB() {
    try {
      if (statement != null) {
        statement.close();
      }
      if (db != null) {
        db.close();
      }
    } catch (Exception e) {
      System.out.println("Could not close the current connection.");
      e.printStackTrace();
    }
  }
}