我有一个由ResultSet填充的JTable。有没有办法计算特定列的总和并将其添加到同一个表的底行?
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
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);
}
return new DefaultTableModel(data, columnNames);
}
public static void main(String[] args) throws Exception {
// The Connection is obtained
ResultSet rs = stmt.executeQuery("select * from product_info");
// It creates and displays the table
JTable table = new JTable(buildTableModel(rs));
// Closes the Connection
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
如果有一个名为qty的列,有没有办法在表格的底部得到总数?
答案 0 :(得分:1)
希望这有帮助
jTable1.setColumnSelectionAllowed(true);
jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
public void calculate() {
calculate(jTable1, jTable1.getSelectedColumn(), jTable1.getSelectedRows());
}
public void calculate(JTable table, int column, int[] rows) {
int result = 0;
for (int row : rows) {
result += Integer.valueOf(table.getValueAt(row, column).toString());
}
((DefaultTableModel) table.getModel()).addRow(new Object[]{result});
}