how do i get DefaultTableModel rows sum in column in java

how do i get DefaultTableModel rows sum in column in java

To get the sum of all the rows in a column of a DefaultTableModel in Java, you can use the getRowCount and getValueAt methods to iterate over the rows of the table and add up the values in the desired column.

Here's an example of how you could do this:

DefaultTableModel model = ...; // get the DefaultTableModel
int columnIndex = ...; // index of the column to sum

double sum = 0;
for (int row = 0; row < model.getRowCount(); row++) {
  Object value = model.getValueAt(row, columnIndex);
  if (value instanceof Number) {
    sum += ((Number) value).doubleValue();
  }
}
Source:ww‮.w‬lautturi.com

This code will iterate over all the rows of the table, retrieve the value at the specified column index for each row, and add it to the sum variable if it is a Number (e.g. an Integer, Double, etc.).

You can then use the sum variable to get the total sum of the values in the specified column.

Keep in mind that this code assumes that all the values in the specified column are numbers. If there are any non-numeric values in the column, they will be ignored. You may want to add additional error handling or type checking to handle these cases.

Created Time:2017-11-01 12:05:08  Author:lautturi