首页定义了一个公用Model类,代码如下:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TableModel;
import java.sql.ResultSet;
import java.util.LinkedList;
import javax.swing.table.AbstractTableModel;
import zhinengkaiguanjiankong.comm.LoggerUtil;
/**
*数据库和JTable数据绑定记录数据存放对象
* @author http://www.my400800.cn
*/
public class TableModel extends AbstractTableModel {
private int column = 4;
private String[] columnName = null;
private LinkedList<String[]> resultSet = null;
public TableModel() {
}
/** Creates a new instance of TableModel */
public TableModel(ResultSet rs, String[] DScolumnName, String[] columnName) throws Exception {
if (DScolumnName.length != columnName.length) {
throw new Exception("指定JTable列和指定数据库列数不一致,无法进行数据绑定");
}
this.columnName = columnName;
column = columnName.length;
resultSet = new LinkedList<String[]>();
try {
while (rs.next()) {
String[] row = new String[column];
for (int i = 0; i < column; i++) {
row[i] = rs.getString(DScolumnName[i]);
}
resultSet.add(row);
}
} catch (Exception e) {
LoggerUtil.WriteErrLog(e);
throw e;
// System.out.println("err");
}
}
/**
* 取得总记录数
* @return 总记录数
*/
public int getRowCount() {
return resultSet.size();
}
/**
* 取得总列数
* @return 总列数
*/
public int getColumnCount() {
return column;
}
/**
* 取得指定行指定列数据
* @param rowIndex 行
* @param columnIndex 列
* @return
*/
public Object getValueAt(int rowIndex, int columnIndex) {
String[] row = resultSet.get(rowIndex);
return row[columnIndex];
}
/**
* 取得指定列名称
* @param i 指定列
* @return 指定列名称返回
*/
public String getColumnName(int i) {
return columnName[i];
}
}
model实现类,在这个列里面设定JTable列明和数据库的取得字段名
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TableModel;
import java.sql.ResultSet;
/**
*
* @author 173.114
*/
public class ZhinengkaiguanjiankongViewTableModel extends TableModel {
public ZhinengkaiguanjiankongViewTableModel(ResultSet rs) throws Exception {
/**
* 记录rs 数据库字段名 JTable列明
*/
super(rs, new String[]{"id", "i64val", "timeval", "val14", "val22", "adv", "val24", "val13"},
new String[]{"ID", "名称", "时间", "状态", "段位", "属性", "备注", "开关ID"});
}
}
数据绑定代码
tableModel = new ZhinengkaiguanjiankongViewTableModel(数据库取得的ResultSet );
jtbl_DataList.setModel(tableModel);
通过上面的代码,就把数据通过Model绑定到JTable了