我创建了一个名为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++;
}
'我'和' 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。
在Cart类中调用顺序的方法,这也是(Cart.java.59):
public Order getOrder(int i) {
return contents.get(i);
}
在课程中增加和减少数量的方法:
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;
}
答案 0 :(得分: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());
.....
}