创建和配置JTable组件的另一种方法是使用表模型。表模型比使用数组或向量作为表的数据源更可取。
创建表模型的最简单方法是扩展AbstractTableModel实现该TableModel接口的抽象类。该AbstractTableModel工具实现表模型的标准行为。它实现了TableModel接口的几乎所有方法,除了三种方法。
这三种方法分别是getValueAt(int rowIndex, int columnIndex)方法,getRowCount()方法和getColumnCount()方法。下面的代码向您展示如何创建表模型。package org.nhooo.example.swing;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
public class TableModelDemo extends JPanel {
public TableModelDemo() {
initializePanel();
}
private void initializePanel() {
// 创建PremiereLeagueTableModel的实例
PremiereLeagueTableModel tableModel =
new PremiereLeagueTableModel();
// 使用TableModel创建JTable的实例
// 作为构造函数参数。
JTable table = new JTable(tableModel);
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
this.setPreferredSize(new Dimension(500, 200));
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
public static void showFrame() {
JPanel panel = new TableModelDemo();
panel.setOpaque(true);
JFrame frame = new JFrame("Premiere League - 2018/2019");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
class PremiereLeagueTableModel extends AbstractTableModel {
// TableModel的列名
private String[] columnNames = {
"TEAM", "P", "W", "D", "L", "GS", "GA", "GD", "PTS"
};
// TableModel的数据
private Object[][] data = {
{ "Liverpool", 3, 3, 0, 0, 7, 0, 7, 9 },
{ "Tottenham", 3, 3, 0, 0, 8, 2, 6, 9 },
{ "Chelsea", 3, 3, 0, 0, 8, 3, 5, 9 },
{ "Watford", 3, 3, 0, 0, 7, 2, 5, 9 },
{ "Manchester City", 3, 2, 1, 0, 9, 2, 7, 7 }
};
/**
* Returns the number of rows in the table model.
*/
public int getRowCount() {
return data.length;
}
/**
* Returns the number of columns in the table model.
*/
public int getColumnCount() {
return columnNames.length;
}
/**
* Returns the column name for the column index.
*/
@Override
public String getColumnName(int column) {
return columnNames[column];
}
/**
* Returns data type of the column specified by its index.
*/
@Override
public Class> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
/**
* Returns the value of a table model at the specified
* row index and column index.
*/
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showFrame();
}
});
}
}