Sum up the last column of JTable

I have multiple JSpinner. When it is clicked, the name,quantity and price will be added into JTable. I also have one JTextField, used to sum up the total price, which is in the last column of the table.

To get the total of the last column of each row, I use this code

Example (Correct)

When I change the qty from 2 to 1, it sum up instead of minus

Learning language is easy but learning basics is difficult

Dave Tolls

Ranch Foreman

Posts: 3061

37

posted 3 months ago

Where is the variable total declared?
It looks like it's not local to the method, so the value is retained between calls to stateChanged.

Well, think it through.
At the moment you have a "global" total value and, when the user changes a number in the table, you then add the new value for that row to this total.

So in your example, your total value was 17, the user changes the value in one row so it now says 6. Your code adds that 6 to the total...so it's now 23.

So what should be done to ensure the total is calculated correctly?

Rob Camick

Ranch Hand

Posts: 2828

15

posted 3 months ago

2

Don't keep a "total" variable.

Instead, whenever any of the values in your table change that will affect the total, simply iterate through all the rows in the table to recalculate the total.

This way you don't need to how the values change. That is if the quantitly goes from 2 to 3, or 2, to 1, the logic is still the same, you don't need to worry about calculating the difference from the previous value.

Rob Camick wrote:Don't keep a "total" variable.
simply iterate through all the rows in the table to recalculate the total.

Can you explain more on this ?

Learning language is easy but learning basics is difficult

Rob Camick

Ranch Hand

Posts: 2828

15

posted 3 months ago

Well, you already have looping code, but you only ever process one row in the loop.

I am suggesting you get rid of the if condition and recalculate the total as you loop through each row. So before the loop starts you set the total value to 0, then for each row you calculate the row amount and add it to the total. When the loop finishes you then display the total value.

You have a title string in the first row of the table? Why not just use column headers, which aren't part of the table?

But anyway if you're going to have the first row of the table be text strings describing the rest of the rows, then clearly you wouldn't bother trying to include the first row when summing up the rest of the rows, which is where the data actually is.

John Joe wrote:How should I get rid of the first row of JTable in order to get the total value ?

That's entirely the wrong way to look at it. Don't get rid of the first row, just don't include it in the rows which you're adding up. There isn't an iron law which says that the index of a Java for-loop must start at zero. Write your loop so that it only covers the rows you want to add up.