日期:2014-05-20 浏览次数:21392 次
package test;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
public class TableModelDemo extends JFrame {
private JTable table;
public TableModelDemo() {
Container container = getContentPane();
addTable(container);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 400);
setLocationRelativeTo(null);
setVisible(true);
}
protected void addTable(Container container) {
String[] columnNames = {"First Name", "Last Name", "Sport",
"# of Years", "Vegetarian"
};
Object[][] rowData = {
{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
};
table = new JTable(new MyTableModel(rowData, columnNames));
table.setFillsViewportHeight(true);
container.add(new JScrollPane(table));
// 设置列宽
TableColumn column = null;
for (int i = 0; i < columnNames.length; ++i) {
column = table.getColumnModel().getColumn(i);
if (2 == i) {
column.setPreferredWidth(150);
} else {
column.setPreferredWidth(50);
}
}
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
TableModel model = table.getModel();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
System.out.println(model.getValueAt(row, column));
}
}
});
}
public static void main(String[] args) {
new TableModelDemo();
}
protected class MyTableModel extends AbstractTableModel {
private String[] columnNames;
private Object[][] rowData;
public MyTableModel(Object[][] rowData, String[] columnNames) {
this.rowData = rowData;
this.columnNames = columnNames;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return rowData.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Class getColumnClass(int col) {
// 如果是boolean,则显示为JCheckBox
// 如果是Integer,则只能输入整数
return getValueAt(0, col).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
// 第一列不能编辑
return col == 0 ? false : true;
}
@Override
public Object getValueAt(int row, int col) {
return rowData[row][col];
}
@Override
public void setValueAt(Object value, int row, int col) {
// 双击时cell editor显示,然后输入值
// 当cell失去焦点或者按下回车键后,setValueAt方法被调用,更新cell renderer
System.out.println("setValuAt: Value: " + value + ", [" + row + ", " + col + "]");
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
}
}