有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JList计算(CVE)的java问题?

我一直在尝试获取我的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();
        }
    }

}

-清单

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

目录项

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) 个答案

  1. # 1 楼答案

    I'm a beginner and don't quite know how to change my code to add a single element from the list.

    阅读ListAPI,您会发现如下方法:

    1. 大小()
    2. 得到(…)

    因此,您创建了一个从0到元素数的循环。在循环中,您从列表中获取元素,并将其添加到签出篮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复制到JListListModel。我更新了我的答案以反映代码的这一部分。我甚至编写了代码来向您展示如何从列表中复制项目

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