在循环中使用按钮调用方法

Calling method with a button in a loop

我创建了一个名为 gPaneCenter 的 gridPane,它旨在创建一个 table。当我将一个项目添加到网格时,它会调用 mehtod addRow(),请看下面:

public static void addRow() {
    System.out.println("Test");
    Label prodDes = new Label(String.valueOf(Controller.shoppingCart.getOrder(i).getProduct().getDescription()));
    Label prodPrice = new Label(String.valueOf(Controller.shoppingCart.getOrder(i).getProduct().getUnitPrice()));
    Label prodQuant = new Label(String.valueOf(Controller.shoppingCart.getOrder(i).getQuantity()));
    Label prodCost = new Label(String.valueOf(Controller.shoppingCart.getOrder(i).getCost()));

    HBox quantityChanger = new HBox();
    Button decreaseQuantBut = new Button("-");
    Button increaseQuantBut = new Button("+");


    decreaseQuantBut.setOnAction(e -> Controller.shoppingCart.getOrder(i).decreaseQuantity());
    increaseQuantBut.setOnAction(e -> Controller.shoppingCart.getOrder(i).increaseQuantity());

    quantityChanger.getChildren().addAll(decreaseQuantBut,prodQuant,increaseQuantBut);

    View.gPaneCenter.addRow(l, prodDes,prodPrice,quantityChanger,prodCost);
    l++;
    i++;
}

'i' 和 'l' 在开头声明:

static int i = 0;
static int l = 1;

添加项目时生成以下 GUI:

当我单击“-”按钮或“+”按钮时,我想分别减少数量和增加数量,但是当我单击任一按钮时出现以下错误:

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at model.Cart.getOrder(Cart.java:59)

这表明它找不到订单,但它可以成功找到打印以下内容的订单:prodDes、prodPrice 和 prodQuant。

在class购物车中调用订单的方法,这也是(Cart.java.59):

    public Order getOrder(int i) {
    return contents.get(i);
}

class订单增减数量方法:

    public void increaseQuantity() {
    quantity++;
}

public void decreaseQuantity() {
    quantity--;
}

用于获取 prodQuant 和 prodCost 的方法(prodDes 和 prodUnitPrice 通过 getProduct() ):

    public int getCost() {
    return quantity * item.getUnitPrice();
}

public Product getProduct() {
    return item;
}

public int getQuantity() {
    return quantity;
}

您使用 i 来标识某一行,但是当您添加更多行时 i 的值会发生变化。

public static void addRow() {   
    int rowNum = i; //solution: a local variable to keep current i value  
     .....
    decreaseQuantBut.setOnAction(e -> Controller.shoppingCart.getOrder(rowNum).decreaseQuantity());
    increaseQuantBut.setOnAction(e -> Controller.shoppingCart.getOrder(rowNum).increaseQuantity());
    .....
}