import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
public class ResultTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = 1L;
boolean DEBUG = false;
private String[] columnNames;
private Object[][] data;
public ResultTableModel(ResultSet rs, String[] columnNames) {
ResultSetMetaData meta;
if (rs != null) {
this.columnNames = columnNames;
try {
meta = rs.getMetaData();
int rowcount = 0, colcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.first();
}
colcount = meta.getColumnCount();
data = new Object[rowcount][colcount];
int i = 0;
do {
for (int j = 0; j < colcount; j++) {
data[i][j] = rs.getObject(j + 1);
}
i++;
} while (rs.next());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(final int col) {
return columnNames[col];
}
public Object getValueAt(final int row, final int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn't implement this method, then the last column would
* contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(final int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(final int row, final int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's data can change.
*/
public void setValueAt(final Object value, final int row, final int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
Wednesday, January 21, 2009
[Java] Creating JTable from Resultset
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment