JList计算(CVE)的问题?

时间:2015-03-25 17:34:02

标签: java swing

我一直试图获得我的Jlist中所有元素的运行总价格,因为它们被添加但是似乎无法让它工作。我试图提供必要的类来重现我的问题,以便更清楚地了解我正在尝试做什么。谢谢。

- 主GUI

public class PaymentSystemGUI extends javax.swing.JFrame {
    private JLabel priceLabel;
    private JLabel totalLabel;
    private JTextField totalField;
    private JButton scanBtn;
    private JList checkoutList;
    private JScrollPane jScrollCheckout;
    private JLabel jLabel1;
    private JButton removeBtn;
    private JButton addBtn;
    private JTextField priceField;
    private JTextField barcodeField;
    private JLabel barcodeLabel;
    private JTextField itemNameField;
    private JLabel jItemName;
    private JLabel editorLabel;
    private JScrollPane checkScrollPane;
    private JScrollPane jScrollPane1;
    private JMenuItem exitButton;
    private JMenu StartButton;
    private JMenuBar MainMenBar;
    private DefaultListModel Inventory = new DefaultListModel();
    private DefaultListModel checkoutBasket = new DefaultListModel();
    private JList productList;
    private InventoryList stockInst;
    private JFileChooser chooser;
    private File saveFile;
    private boolean changesMade;

    /**
     * Auto-generated main method to display this JFrame
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                PaymentSystemGUI inst = new PaymentSystemGUI();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);

            }
        });
    }

    public PaymentSystemGUI() {
        super();
        initGUI();

        stockInst = new InventoryList();


        productList.setModel(stockInst);
        checkoutList.setModel(checkoutBasket);

    }

    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().setLayout(null);
            getContentPane().setBackground(new java.awt.Color(245, 245, 245));
            this.setEnabled(true);
            {
                MainMenBar = new JMenuBar();
                setJMenuBar(MainMenBar);
                {
                    StartButton = new JMenu();
                    MainMenBar.add(StartButton);
                    StartButton.setText("File");
                    {
                        exitButton = new JMenuItem();
                        StartButton.add(exitButton);
                        exitButton.setText("Exit");
                        exitButton.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                System.exit(0);
                            }
                        }

                        );

                    }

                }


                {
                    jScrollPane1 = new JScrollPane();
                    getContentPane().add(jScrollPane1);
                    jScrollPane1.setBounds(31, 84, 275, 323);
                    jScrollPane1.setAlignmentY(0.4f);
                    {
                        ListModel stockListModel = new DefaultComboBoxModel(
                                new String[] { "Item One", "Item Two" });
                        productList = new JList();
                        jScrollPane1.setViewportView(productList);
                        BorderLayout stockListLayout = new BorderLayout();
                        productList.setLayout(stockListLayout);
                        productList.setBounds(25, 92, 269, 330);
                        productList.setAlignmentX(0.4f);
                        productList.setModel(stockListModel);
                    }
                }
                {
                    editorLabel = new JLabel();
                    getContentPane().add(editorLabel);
                    editorLabel.setText("INVENTORY");
                    editorLabel.setBounds(121, 56, 88, 16);
                }
                {
                    jItemName = new JLabel();
                    getContentPane().add(jItemName);
                    jItemName.setText("Item Name");
                    jItemName.setBounds(31, 432, 61, 16);
                }
                {
                    itemNameField = new JTextField();
                    getContentPane().add(itemNameField);
                    itemNameField.setBounds(127, 426, 130, 28);
                }
                {
                    barcodeLabel = new JLabel();
                    getContentPane().add(barcodeLabel);
                    barcodeLabel.setText("Barcode Number");
                    barcodeLabel.setBounds(27, 476, 94, 16);
                }
                {
                    barcodeField = new JTextField();
                    getContentPane().add(barcodeField);
                    barcodeField.setBounds(127, 470, 130, 28);
                }
                {
                    priceLabel = new JLabel();
                    getContentPane().add(priceLabel);
                    priceLabel.setText("Price of Item");
                    priceLabel.setBounds(33, 521, 68, 16);
                }
                {
                    priceField = new JTextField();
                    getContentPane().add(priceField);
                    priceField.setBounds(127, 515, 130, 28);
                }
                {
                    addBtn = new JButton();
                    getContentPane().add(addBtn);
                    addBtn.setText("Add");
                    addBtn.setBounds(53, 560, 83, 28);

                }
                addBtn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evta) {
                        addButtonPressed();
                    }
                });
                {
                    removeBtn = new JButton();
                    getContentPane().add(removeBtn);
                    removeBtn.setText("Remove");
                    removeBtn.setBounds(148, 560, 83, 28);
                    removeBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            removeButtonPressed();
                        }
                    });

                }
                {
                    jLabel1 = new JLabel();
                    getContentPane().add(jLabel1);
                    jLabel1.setText("CHECKOUT");
                    jLabel1.setBounds(480, 79, 68, 16);
                }
                {
                    jScrollCheckout = new JScrollPane();
                    getContentPane().add(jScrollCheckout);
                    jScrollCheckout.setBounds(395, 107, 248, 323);
                    {
                        ListModel checkoutListModel = 
                                new DefaultComboBoxModel(
                                        new String[] { "Item One", "Item Two" });
                        checkoutList = new JList();
                        jScrollCheckout.setViewportView(checkoutList);
                        checkoutList.setModel(checkoutListModel);
                    }
                }
                {
                    scanBtn = new JButton();
                    getContentPane().add(scanBtn);
                    scanBtn.setText("Scan Item into Checkout");
                    scanBtn.setBounds(59, 613, 161, 28);
                    scanBtn.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            checkoutBasket.addElement(productList.getSelectedValue());
                              double totalAddedValue = 0.00;
                              double oldCheckoutValue   = 0.00;

                              //Iterate to get the price of the new items.
                              for (int i = 1; i < productList.getModel().getSize(); i++) {
                                InventItem item = (InventItem) productList.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 checkoutField = totalField.getText();

                              //Check that cartTextField already contains a value.
                              if(checkoutField != null && !checkoutField.isEmpty())
                              {
                                oldCheckoutValue = Double.parseDouble(checkoutField);
                              }

                              totalField.setText(String.valueOf(oldCheckoutValue  + totalAddedValue));
                              checkoutBasket.addElement(productList);
                            }
                        });
                }
                {
                    totalField = new JTextField();
                    getContentPane().add(totalField);
                    totalField.setBounds(503, 442, 115, 28);
                    totalField.setEditable(false);
                }
                {
                    totalLabel = new JLabel();
                    getContentPane().add(totalLabel);
                    totalLabel.setText("Total Cost of Items");
                    totalLabel.setBounds(367, 448, 124, 16);
                }

                pack();
                this.setSize(818, 730);
            }
        } catch (Exception e) {
            // add your error handling code here
            e.printStackTrace();
        }

    }

    private void loadMenuItemAction() {
        try {
            FileInputStream in = new FileInputStream("itemdata.dat");
            ObjectInputStream oIn = new ObjectInputStream(in);
            stockInst = (InventoryList)oIn.readObject();
            productList.setModel(stockInst);
            oIn.close();


    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Failed to read file");
        System.out.println("Error : " + e);
    }


    }

    private void clearAllTextFields() {
        barcodeField.setText("");
        itemNameField.setText("");
        priceField.setText("");
    }


    private void removeButtonPressed() {
        int selectedIndex = productList.getSelectedIndex();

        if (selectedIndex == -1) {
            JOptionPane.showMessageDialog(this, "Select An Item to Remove");
        } else {
            InventItem toGo = (InventItem)stockInst.getElementAt(selectedIndex);
            if (JOptionPane.showConfirmDialog(this, "Do you really want to remove the item from the cart ? : " + toGo,
                    "Delete Confirmation", JOptionPane.YES_NO_OPTION) 
                    == JOptionPane.YES_OPTION) {
                stockInst.removeItem(toGo.getID());
                clearAllTextFields();
                productList.clearSelection();
            }
        }
    }

    private void addButtonPressed() {
        String newbarcode = barcodeField.getText();
        String newitemName = itemNameField.getText();
        String newprice = priceField.getText();

        if (newbarcode.equals("") || newitemName.equals("") || newprice.equals("")) {
            JOptionPane.showMessageDialog(this, "Please Enter Full Details");
        } else {
            stockInst.addInventItem(newbarcode, newitemName, newprice);
            InventItem newBasket = stockInst.findItemByName(newbarcode);
            productList.setSelectedValue(newBasket, true);
            clearAllTextFields();
        }
    }

}

-InventoryList

import javax.swing.DefaultListModel;

public class InventoryList extends DefaultListModel {
    public InventoryList(){
        super();
    }

    public void addInventItem(String idNo, String itemName, String total){
        super.addElement(new InventItem(idNo, itemName, total));
    }

    public InventItem findItemByName(String name){
        InventItem temp;
        int indexLocation = -1;
        for (int i = 0; i < super.size(); i++) {
            temp = (InventItem)super.elementAt(i);
            if (temp.getItemName().equals(name)){
                indexLocation = i;
                break;
            }
        }

        if (indexLocation == -1) {
            return null;
        } else {
            return (InventItem)super.elementAt(indexLocation);
        }
    }


    public InventItem findItemByBarcode(String id){
        InventItem temp;
        int indexLocation = -1;
        for (int i = 0; i < super.size(); i++) {
            temp = (InventItem)super.elementAt(i);
            if (temp.getID().equals(id)){
                indexLocation = i;
                break;
            }
        }

        if (indexLocation == -1) {
            return null;
        } else {
            return (InventItem)super.elementAt(indexLocation);
        }        
    }

    public void removeItem(String id){
        InventItem empToGo = this.findItemByBarcode(id);
        super.removeElement(empToGo);
    }
}

InventoryItem

import java.io.Serializable;

public class InventItem implements Serializable {

    private String idnum;
    private String itemName;
    private String cost;

    public InventItem() {

    }

    public InventItem (String barno, String in, String price) {
            idnum = barno;
            itemName = in;
            cost = price;
    }

    public String getID(){
        return idnum;
    }

    public String getItemName(){
        return itemName;
    }

    public void setitemName(String itemName){
            this.itemName = itemName;
        }

    public String getPrice(){
        return cost;
    }

    public String toString(){
        return idnum + ": " + itemName + ", £ " + cost;

    }


}

1 个答案:

答案 0 :(得分:2)

  

我是初学者,并且不太清楚如何更改我的代码以从列表中添加单个元素。

阅读List API,您会找到以下方法:

  1. 尺寸()
  2. 得到(...)
  3. 因此,您创建一个循环,从0循环到元素数。在循环内部,您可以从List获取元素并将其添加到checkoutBasket JList的模型中。

    以下是MCVE帮您入门的基础知识。您需要做的就是添加actionPerformed()方法的代码来复制所选项目:

    import java.awt.*;
    import java.awt.event.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    
    public class SSCCE extends JPanel
    {
        JList<String> left;
        JList<String> right;
        JLabel total;
    
    
        public SSCCE()
        {
            setLayout( new BorderLayout() );
    
            // change this to store Integer objects
            String[] data = { "one", "two", "three", "four", "five", "four", "six", "seven" };
            left = new JList<String>(data);
            add(new JScrollPane(left), BorderLayout.WEST);
    
            right = new JList<String>( new DefaultListModel<String>() );
            add(new JScrollPane(right), BorderLayout.EAST);
    
            JButton button = new JButton( "Copy" );
            add(button, BorderLayout.CENTER);
    
            button.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    DefaultListModel<String> model = (DefaultListModel<String>)right.getModel();
                    List<String> selected = left.getSelectedValuesList();
    
                    for (String item: selected)
                        model.addElement( item );
    
                    // add code here to loop through right list and total the Integer items
    
                    total.setText("Selected total is ?");
                }
            });
    
            total = new JLabel("Selected total is 0");
            add(total, BorderLayout.SOUTH);
        }
    
        private static void createAndShowGUI()
        {
            JFrame frame = new JFrame("SSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new SSCCE() );
            frame.setLocationByPlatform( true );
            frame.pack();
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowGUI();
                }
            });
        }
    }
    

    如果您遇到问题,请删除原始代码并根据此答案中的信息发布显示您尝试过的内容的MCVE。不要创建新帖子。

    编辑:

    我的原始答案谈到了从DefaultListModel复制数据。但是,您的代码使用JList.getSelectedValuesList()方法获取List个所选项目。需要将这些项目中的每一项都从List复制到ListModel JList。我更新了我的答案,以反映您的代码的这一部分。我甚至编写了代码来向您展示如何从列表中复制项目。

    所以现在你的下一步是计算“正确”JLIst中的项目总数(即你的结账)。为此,您需要将“左”列表中的数据更改为“整数”对象。所以现在当你复制整数对象时,yo9u可以遍历JList并计算总值。如果您遇到问题,那么您发布的任何代码都应该基于此MVCE,而不是您的真实程序。