【发布时间】:2015-03-24 20:39:51
【问题描述】:
我正在创建一个购物车模拟,其中包含一个产品列表作为我的库存,一个列表用作用户可以扫描物品的购物车。理论上,这是将总成本显示为列表下方的 JTextField 中的项目,因为它们被添加到购物篮中。
扫描物品我有以下方法:
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
//Iterate to get the price of the new items.
for (int i = 0; i < list.getModel().getSize(); i++) {
CartItem item = (CartItem) list.getModel().getElementAt(i);
totalAddedValue += Double.ParseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
string cartFieldText = cartTotalField.getText();
//Check that cartTextField already contains a value.
if(cartTextField != null && !cartTextField.isEmpty())
{
oldCartValue = Double.parseDouble(cartFieldText);
}
cartTotalField.setText(String.valueOf(oldCartValue + totalAddedValue));
checkoutBasket.addElement(list);
}
目前我的主要问题是,将一件商品扫描到购物车中会显示库存列表中所有商品的总和,而不仅仅是我要扫描的一件商品。它还将在项目名称下打印一行,例如 javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... 。我该如何解决这个问题?
项目列表类
public class StockList extends DefaultListModel {
public StockList(){
super();
}
public void addItem(String barcodeNo, String itemName, String price){
super.addElement(new Item(barcodeNo, itemName, price));
}
public Item findItemByName(String name){
Item temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (Item)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (Item)super.elementAt(indexLocation);
}
}
public Item findItemByBarcode(String id){
Item temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (CheckoutItem)super.elementAt(i);
if (temp.getBarcodeNo().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (Item)super.elementAt(indexLocation);
}
}
public void Item(String id){
Item empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
【问题讨论】: