如何计算JList元素的总和?

时间:2015-03-24 20:39:51

标签: java swing sum

我创建了一个购物车模拟,其中包含产品列表作为我的库存和用作购物车的列表,用户可以将项目扫描到其中。理论上,这是将总成本显示为列表下方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 ....我怎么能解决这个问题?

ItemList类

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);
}

}

1 个答案:

答案 0 :(得分:0)

javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... .

这是JList的toString()表示。 JList默认渲染器只调用添加到ListModel的任何对象的toString()方法。

checkoutBasket.addElement(list);

不要将JList添加到结帐篮子。您必须将列表中的每个项目分别添加到结帐篮子。

相关问题