Codenameone 代号一:如何计算每个按钮迭代的运行总数?

Codenameone 代号一:如何计算每个按钮迭代的运行总数?,codenameone,cumulative-sum,Codenameone,Cumulative Sum,我想计算每次按下按钮时的运行总数。它应该加上一个数量加上总数量(如果按钮已经按下)。下面是我的代码片段 TextField quantity = new TextField("", "Volume of water (ml)", 4, TextArea.ANY); intake.addComponent(quantity); Button add = new Button("Add"); intake.addComponent(add); ... int total = 0; //---

我想计算每次按下按钮时的运行总数。它应该加上一个数量加上总数量(如果按钮已经按下)。下面是我的代码片段

TextField quantity = new TextField("", "Volume of water (ml)", 4, TextArea.ANY);
intake.addComponent(quantity);

Button add = new Button("Add");
intake.addComponent(add);

...

int total = 0;

//--------------------------------------------------------------
add.addActionListener((ActionEvent ev) -> {
Storage s = Storage.getInstance();

try {

    String num = quantity.getText();
    Integer num2 = Integer.parseInt(num);

    String name = itemName.getText();

    total += num2;
    Dialog.show("", "You have consumed a total of " + Integer.toString(total) + "ml of water", "OK", "Close");

... 

} catch {
    ... 
}

});
对于上面的代码,下面的代码段出现错误(“从lambda表达式引用的局部变量必须是final或实际上是final”)。我也尝试过“public void actionPerformed()”方法,但没有成功

total += num2;
Dialog.show("", "You have consumed a total of " + Integer.toString(total) + "ml of water", "OK", "Close");

因此,我将非常感谢任何关于如何编写一个运行总数的帮助和指导。

total
成为你们班的一员。由于lambda(事件调用)可能并行发生,因此更改lambda中的total可能会产生非法状态(从技术上讲,事件不能并行发生,但Java编译器不知道这一点,并且不允许非最终访问)。

您可以使用一种方法作为替代方法,例如将调用的increaseTotal,而不是直接操作total变量。正如Shai所提到的,事件不能并行发生,所以无需添加同步标记或其他

public void increaseTotal(int addedValue){
     this.total += addedValue;
}