I have a JTable which is being populated by a ResultSet. Is there any way to calculate the sum of a specific column and add it to the bottom row of the same table?
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));
}
If there is a column called qty is there a way to get the total at the bottom of the table?
Hope this helps
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});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.