繁体   English   中英

从arraylist元素获取特定值

[英]get specific value from arraylist element

抱歉,这是一个简单的答案,或者已经被回答,但是已经搜索并且找不到任何东西。 我目前正在使用DefaultListModel中的产品创建超市结帐行,每个产品都有名称,价格,重量和代码,如下所示

public class Product {
private String name;
private double weight;
private double price;
private int code;

public Product (){
}

public Product (String Name, double kg, double pounds, int id){
name = Name;
weight = kg;
price = pounds;
code = id;

public String toString (){
return name + " - " + "£" + price + "    Product # " + code;

和产品列入清单

public class productList extends DefaultListModel {
public productList (){
    super();
}
public void addProduct (String name, double weight, double price, int code){
super.addElement(new Product(name, weight, price, code));

这已在GUI中用于代码段中的签出,如下所示

private DefaultListModel defaultMainList = new DefaultListModel();
//other code
currentBasket.setModel(defaultMainList); //currentBasket is name of jlist

    productsList = new productList();

    productsList.addProduct("bananas", 0.5, 0.99, 1);
    productsList.addProduct("apples", 0.8, 1.39, 2);
    //etc etc, other products emitted
    mainCheckoutList.setModel(productsList);
    //unimportant code
addBasketItem = new JButton();
        getContentPane().add(addBasketItem);
        addBasketItem.setText("Add >");
        addBasketItem.setBounds(215, 108, 62, 31);
        addBasketItem.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent e){
                    defaultMainList.addElement(productsList.getElementAt(mainCheckoutList.getSelectedIndex()));
                mainTillPrice.setText((defaultMainList.toString()));

当前代码将此项目从左侧的jlist(主要结帐列表,这是我的可用产品列表)添加到右侧的jlist(我的购物篮)。 它还将右边列表中的整个字符串添加到名为mainTillPrice的jtextfield中,我想知道是否有任何方法可以添加价格,例如。 为香蕉对象添加0.99,然后在添加了后续项目的同时添加其价格,以保持总计。 任何帮助将不胜感激,并再次抱歉对解释或代码中的任何问题,我很新。

好吧,我不会使用defaultMainList.toString() 您将需要获取已添加的Product ,获取Productprice并将其添加到当前理货中。 然后需要将该值添加到mainTillPrice文本字段中

public void actionPerformed (ActionEvent e){
    Product product = (Product)mainCheckoutList.getSelectedItem();
    defaultMainList.addElement(product);
    runningTally += product.getPrice();
    mainTillPrice.setText(NumberFormat.getCurrencyInstance().format(runningTally));

这将需要您创建一个名为runningTally的实例字段,并假定您的Product有一个getPrice方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM