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

Tho*_*mas 3 java javafx increment button

我创建了一个名为gPaneCenter的gridPane,用于创建表.当我将一个项目添加到网格时,它将调用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++;
}
Run Code Online (Sandbox Code Playgroud)

'i'和'l'在开始时声明:

static int i = 0;
static int l = 1;
Run Code Online (Sandbox Code Playgroud)

在添加项目时会生成以下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)
Run Code Online (Sandbox Code Playgroud)

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

在类Cart中调用命令的方法,这也是(Cart.java.59):

    public Order getOrder(int i) {
    return contents.get(i);
}
Run Code Online (Sandbox Code Playgroud)

增加和减少课程数量的方法顺序:

    public void increaseQuantity() {
    quantity++;
}

public void decreaseQuantity() {
    quantity--;
}
Run Code Online (Sandbox Code Playgroud)

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

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

public Product getProduct() {
    return item;
}

public int getQuantity() {
    return quantity;
}
Run Code Online (Sandbox Code Playgroud)

c0d*_*der 5

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());
    .....
}
Run Code Online (Sandbox Code Playgroud)