Friday, October 22, 2021

Populate JTable from ResultSet

Every once in a while we need to populate data in a JTable. Here's a simple to use DefaultTableModel for populating a JTable from a ResultSet.


public DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {

ResultSetMetaData metaData = rs.getMetaData();

Vector columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}

Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}

DefaultTableModel dtm = new DefaultTableModel(data, columnNames) {

private static final long serialVersionUID = 1L;

@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};

return dtm;

}

No comments:

Post a Comment

Ever feel like no one is listening?

 Ever have that feeling that no one is listening to you? Yeah, that feeling. It can be a strong feeling to have, a hurtful feeling also. The...