Taimur Khan
Taimur Khan

Reputation:

getting sum of jtable values continuously

I want to get the sum of all the values from jtable continuously. Like I have made a jtable where the user will put data continuously and whenever a new row will insert in the jtable then some code should execute for taking all the sum of values of jtable and then set it on a text filed. I have written the code but I don't that in which event I should use the code so that when a new row is inserted in the table then the code runs and get the new sum of all values and store in a text field. So now in which method of jtable I should use this code so when a new row is inserted so that code executes. The code is here...

    int rows=productionTable.getRowCount();
    int totalBundles=0;
    int totalBoxes=0;

    //totalBundles
    for(int i=0;i<rows;i++)
    {
        totalBundles=totalBundles+Integer.parseInt(productionTable.getValueAt(i, 1)+"");

    }
    this.totalBundlesTextField.setText(totalBundles+"");
    //

    //totalBoxes
    for(int i=0;i<rows;i++)
    {
        totalBoxes=totalBoxes+Integer.parseInt(productionTable.getValueAt(i, 2)+"");

    }
    this.totalBoxesTextField.setText(totalBoxes+"");
    //

Upvotes: 0

Views: 62

Answers (1)

camickr
camickr

Reputation: 324098

So now in which method of jtable I should use this code so when a new row is inserted so that code execute

You do this when the data in the TableModel changes. So you can add a TableModelListener to the TableModel of your table. Then a TableModelEvent will be generated when you:

  1. add rows of data
  2. remove rows of data
  3. change the value of existing data

In each of the above cases you could then iterate through the TableModel to calculate the new value.

Check out JTable -> TableModeListener for a simple example of use a TableModelListener.

The above approach assumes that you don't have a lot a data in your model, since it recalculates the value each time a change is made.

If you have a lot of data this is not very efficient so you may want to keep a running total of the value in your TableModel. So you would need to customize the TableModel to keep a total. And then in methods like setValueAt(...), insertRow(...), removeRow(...) you would need to add logic to update the total as the model is updated.

Upvotes: 1

Related Questions