问题
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));
回答1:
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.
来源:https://stackoverflow.com/questions/35640634/suming-a-specific-tableview-column-row-in-javafx