gpt4 book ai didi

java - JList 计算 (CVE) 存在问题?

转载 作者:行者123 更新时间:2023-12-02 04:50:42 24 4
gpt4 key购买 nike

我一直在尝试获取 Jlist 中添加的所有元素的运行总价,但似乎无法使其正常工作。我试图提供必要的类来重现我的问题,以便更清楚地了解我正在尝试做的事情。谢谢。

-主图形用户界面

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;

}


}

最佳答案

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

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

  1. 大小()
  2. 获取(...)

因此,您创建了一个从 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 复制到 JListListModel。我更新了我的答案以反射(reflect)您的代码的这一部分。我什至编写了代码来向您展示如何从列表中复制项目。

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

关于java - JList 计算 (CVE) 存在问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com