在 JavaFX 中使用特定的 TableView column/row

Suming a specific TableView column/row in JavaFX

我在 java 中完成了此操作,其中我对价格 column/row 的值求和。但我想知道如何在 JavaFX 中执行此操作。

我想对第 1 列中的所有内容求和并将其显示在 inputField 中,我在 java 中使用它来完成,但您如何在 JavaFX 中执行此操作?

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

这是我正在尝试做的事情:

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));

如果你真的有一个TableView<Integer>,好像是你在评论里说的那样,你就可以

TableView<Integer> table = ... ;

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

或者,使用 Java 8 方法:

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

如果您为 table 使用实际模型 class 进行了更标准的设置,那么您将需要遍历项目列表并对每个项目调用适当的 get 方法,然后将结果添加到总数中。例如。像

TableView<Item> table = ...;

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

或者,再次采用 Java 8 样式

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

这两个假设您有一个 Item class 和 getPrice() 方法,并且相关列显示 price 属性每一项。

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