CookieMonster
CookieMonster

Reputation: 321

Suming a specific TableView column/row in JavaFX

I have done this in java where I sum the values of the price column/row. But I am wondering how to do this in JavaFX.

I want to sum everything in column 1 and display it in a inputField, I used this to do it in java but how do you do this in JavaFX?

tableview.getValueAt(i, 1).toString();

Here is what I'm trying to do:

int sum = 0;

for (int i = 0; i < tableview.getItems().size(); i++) {
    sum = sum + Integer.parseInt(tableview.getValueAt(i, 1).toString());
}

sumTextField.setText(String.valueOf(sum));

Upvotes: 2

Views: 6857

Answers (2)

jerry kabemba
jerry kabemba

Reputation: 1

public void totalCalculation (){

   double TotalPrice = 0.0;
    TotalPrice = Yourtable.getItems().stream().map(
            (item) -> item.getMontant()).reduce(TotalPrice, (accumulator, _item) -> accumulator + _item);

          TexfieldTotal.setText(String.valueOf(TotalPrice));
}
//getMontant is the getter of your column 

Upvotes: 0

James_D
James_D

Reputation: 209694

If you really have a TableView<Integer>, which seems to be what you are saying in the comments, you can just do

TableView<Integer> table = ... ;

int total = 0 ;
for (Integer value : table.getItems()) {
    total = total + value;
}

or, using a Java 8 approach:

int total = table.getItems().stream().summingInt(Integer::intValue);

If you have a more standard set up with an actual model class for your table, then you would need to iterate through the items list and call the appropriate get method on each item, then add the result to the total. E.g. something like

TableView<Item> table = ...;

int total = 0 ;
for (Item item : table.getItems()) {
    total = total + item.getPrice();
}

or, again in Java 8 style

int total = table.getItems().stream().summingInt(Item::getPrice);

Both of these assume you have an Item class with a getPrice() method, and the column in question is displaying the price property of each item.

Upvotes: 3

Related Questions