如何计算购物车JList中的价格总和?

时间:2020-04-08 06:28:16

标签: java swing jlist

我一直在创建此库存程序,该程序从txt文件获取产品ID,名称,商品价格和库存。它将其导入到我的产品列表(JList)中,然后当我按“添加到购物车”按钮时,它将把选定的产品移动到购物车(另一个JList)。

我的主要问题是,如何计算购物车中所有价格的总和?如何将产品的价格与特定价格绑定?假设要显示总价,我使用的是JLabel

以下是一些图片和代码:

My inventory program

这是到目前为止的“移动”按钮的代码:

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == movebutton) {
    model2.addElement(list.getSelectedValue());

    }

这是显示商品的图片,商品名称,价格和库存的代码:

public void valueChanged(ListSelectionEvent e) {
    try {
        String gadgets = (String) c1.getSelectedItem();  //when the combobox is selected
        switch (gadgets) {
            case "Consoles":  //selects first product category
                image.setIcon(graphicsconsole[list.getSelectedIndex()]);  //sets the image

                File file = new File("stock\\consoles\\consoles.txt"); //reads the txt file 
                int ctr = 0;
                try {
                    Scanner s1 = new Scanner(new File(String.valueOf(file)));
                    while (s1.hasNextLine()) {
                        ctr = ctr + 1;
                        s1.next();
                        s1.next();
                        s1.next();
                        s1.nextLine();
                    }
                    String[] ID = new String[ctr];
                    String[] PRICE = new String[ctr];
                    String[] STOCK = new String[ctr];
                    String[] NAME = new String[ctr];

                    Scanner s2 = new Scanner(new File(String.valueOf(file)));  //creates strings
                    for (int i = 0; i < ctr; i = i + 1) {
                        ID[i] = s2.next();
                        PRICE[i] = s2.next();
                        STOCK[i] = s2.next();
                        NAME[i] = s2.nextLine();

                iteminfo.setText(NAME[list.getSelectedIndex()]);  //shows the item name
                itemdescription.setText(" P " + PRICE[list.getSelectedIndex()]);  //shows the price
                itemstock.setText(" Stock: "+ STOCK[list.getSelectedIndex()]); //shows the stock
                    }
                } catch (Exception a) {
                    a.printStackTrace();
                }break;

我是否需要一个空数组并在其中添加值?不在购物车中时,如何删除值?抱歉,如果我的帖子/问题听起来令人困惑,我希望它是可以理解的。

0 个答案:

没有答案