使用多个项目更新字符串

时间:2016-01-19 22:24:03

标签: java swing jtextarea

所以我有一个显示项目名称+数量+价格的字符串,它被附加到JTextfield容器。

例如

Bath towel 3 5.5
Gorilla suit 3 30.0
Whizz games console 3 50.0

如果有人现在再添加一条浴巾,它将会是:

Bath towel 3 5.5
Gorilla suit 3 30.0
Whizz games console 3 50.0
Bath towel 1 5.5

而不是我想要将第一行更新为Bath Towel 4 5.5而不是在下面添加,我不知道如何实现我正在考虑添加我将在每次有人显示和更新的数组点击添加

以下是代码:

public void actionPerformed(ActionEvent ae) {
    int amountInt = (Integer)amount.getValue();
    String item = stocksDropdown.getSelectedItem().toString();
    double price = getPriceForName(item);
    String orderItem;
    if(ae.getSource() == add){
        if(amountInt>0){
            orderItem = item+" "+Integer.toString(amountInt)+" "+price+"\n";
            order.append(orderItem);
        }else if(amountInt == 0){

            //delete from array
        }
    }
}

更新股票代码:

public class StockData {

    public static class Item {

        Item(String n, double p, int q) {
            name = n;
            price = p;
            quantity = q;
        }

        // get methods
        public String getName() {
            return name;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        // instance variables 
        private final String name;
        private final double price;
        private int quantity;
    }

    private final static Map<String, Item> stock = new HashMap();

    static {

        stock.put("00", new Item("Bath towel", 5.50, 10));
        stock.put("11", new Item("Plebney light", 20.00, 5));
        stock.put("22", new Item("Gorilla suit", 30.00, 7));
        stock.put("33", new Item("Whizz games console", 50.00, 8));
        stock.put("44", new Item("Oven", 200.00, 4));
    }
    public static Map<String, Item> getStock() {
        return stock;
       }
    public static String getName(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return null; // null means no such item
        } else {
            return item.getName();
        }
    }

    public static double getPrice(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return -1.0; // negative price means no such item
        } else {
            return item.getPrice();
        }
    }

    public static int getQuantity(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return -1; // negative quantity means no such item
        } else {
            return item.getQuantity();
        }
    }

    public static void update(String key, int extra) {
        Item item = stock.get(key);
        if (item != null) {
            item.quantity += extra;
        }
    }


}

2 个答案:

答案 0 :(得分:0)

实际上,您应该重新设计您的appilcation,而不是高级别的String操作。 将所有数据保存在字符串中是一个非常脆弱,复杂和危险的举动。

为您使用的产品使用课程。 将数据保存在对象中。 在GUI交互之后更新relavant对象。

只有完成所有操作后,您才能编译所有数据,并将其写入JTextArea或JList或JTable。

答案 1 :(得分:0)

这是示例代码。它全部包含在一个文件中。 在您的项目中,为了清楚起见,您应该将每个顶级类放入其自己的文件中。

BE REMINDED 此对象处理仅适用于单实例类。如果您想在多实例应用程序上添加/删除购物车项目,则应该克隆项目或使用工厂方法或复制构造函数以确保您的项目统计信息不会与其他项目混淆买客户。

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.MutableComboBoxModel;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.table.AbstractTableModel;

/**
 * This is a tool class I'd keep in a library, useful to re-use.
 * @author JayC667
 * @param <T> Class type of Items to be contained
 */
class ArrayListModel<T> implements MutableComboBoxModel<T> {

    private final List<T>                       mData;
    private final ArrayList<ListDataListener>   mListeners  = new ArrayList<>();

    private T                                   mSelectedItem;

    public ArrayListModel() {
        mData = new ArrayList<>();
    }

    public ArrayListModel(final List<T> pList) {
        mData = pList;
    }

    public ArrayListModel(final Collection<T> pCollection) {
        this();
        mData.addAll(pCollection);
    }

    public ArrayListModel(final Iterable<T> pIterable) {
        this();
        for (final T t : pIterable) {
            mData.add(t);
        }
    }

    @SafeVarargs public ArrayListModel(final T... pItemsArray) {
        this();
        for (final T t : pItemsArray) {
            mData.add(t);
        }
    }

    public void fireDataChangedEvent() {
        final ListDataEvent e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize());
        for (final ListDataListener l : mListeners) {
            l.contentsChanged(e);
        }
    }

    @Override public int getSize() {
        return mData.size();
    }
    @Override public T getElementAt(final int pIndex) {
        return mData.get(pIndex);
    }
    @Override public void addListDataListener(final ListDataListener pL) {
        System.out.println("ArrayListModel.addListDataListener() " + pL);
        mListeners.add(pL);
    }
    @Override public void removeListDataListener(final ListDataListener pL) {
        System.out.println("ArrayListModel.removeListDataListener() " + pL);
        mListeners.remove(pL);
    }
    @SuppressWarnings("unchecked") @Override public void setSelectedItem(final Object pAnItem) {
        System.out.println("ArrayListModel.setSelectedItem()");
        mSelectedItem = (T) pAnItem;
    }
    @Override public Object getSelectedItem() {
        System.out.println("ArrayListModel.getSelectedItem()");
        return mSelectedItem;
    }
    @Override public void addElement(final T pItem) {
        mData.add(pItem);
    }
    @Override public void removeElement(final Object pObj) {
        mData.remove(pObj);
    }
    @Override public void insertElementAt(final T pItem, final int pIndex) {
        mData.add(pIndex, pItem);
    }
    @Override public void removeElementAt(final int pIndex) {
        mData.remove(pIndex);
    }

}



class Item {
    public final String mName;          // as these are final, you can make em public with no worries
    public final int    mPriceCents;
    private int         mQuantity;      // NOT final, use getters and setters!

    public Item(final String pName, final int pPriceCents) {
        mName = pName;
        mPriceCents = pPriceCents;
    }

    public int getQuantity() {
        return mQuantity;
    }
    public void setQuantity(final int pQuantity) {
        mQuantity = pQuantity;
    }

    @Override public String toString() {
        return mName;
    }

// equals and hashCode are needed for the hashmap/set; 
@Override public boolean equals(final Object pObj) {
    if (!(pObj instanceof Item)) return false;
    final Item o = (Item) pObj;
    return mName.equals(o.mName) && mPriceCents == o.mPriceCents;
}
@Override public int hashCode() {
    return mName.hashCode() + mPriceCents;
}

}



class OrderPanel extends JPanel {
    private static final long   serialVersionUID    = 6667651987287570825L;

    static private void flattenComponent(final JComponent pComponent) {
        pComponent.setMaximumSize(new Dimension(pComponent.getMaximumSize().height, pComponent.getPreferredSize().width));
    }

    private final JComboBox<Item>   gLstItems;
    private final JTextField        gTxtName;
    private final JTextField        gTxtPrice;
    private final JTextField        gTxtQuantity;

    private final Market            mMarket;

    public OrderPanel(final Market pMarket) {
        mMarket = pMarket;
        setBorder(new TitledBorder("Order Panel"));
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        add(new JLabel("Select Product"));
        gLstItems = new JComboBox<>(mMarket.getStockModel());
        flattenComponent(gLstItems);
        gLstItems.addActionListener((PActionEvent) -> loadItemToGUI());
        add(gLstItems);

        add(new JLabel("Product Name"));
        add(gTxtName = new JTextField());
        flattenComponent(gTxtName);
        gTxtName.setEditable(false);

        add(new JLabel("Product Price"));
        add(gTxtPrice = new JTextField());
        flattenComponent(gTxtPrice);
        gTxtPrice.setEditable(false);

        add(new JLabel("Order Quantity"));
        add(gTxtQuantity = new JTextField());
        flattenComponent(gTxtQuantity);

        final JButton orderButton = new JButton("Add to Cart");
        orderButton.addActionListener((pEvent) -> addSelectedItemToCart());
        add(orderButton);

        add(Box.createVerticalGlue());

        for (final Component c : getComponents()) {
            final JComponent cc = (JComponent) c;
            cc.setAlignmentX(0);
        }
    }


    private void loadItemToGUI() {
        final Item i = (Item) gLstItems.getSelectedItem();
        if (i == null) return;
        gTxtName.setText(i.mName);
        gTxtPrice.setText("" + (float) i.mPriceCents / 100);
        gTxtQuantity.setText("0");
    }

    private void addSelectedItemToCart() {
        try {
            final Item item = (Item) gLstItems.getSelectedItem();
            if (item == null) throw new IllegalArgumentException("No item selected!");

            final int addQuantity = Integer.parseInt(gTxtQuantity.getText());
            final int newQuantity = Math.max(item.getQuantity() + addQuantity, 0); // prevent sub-selling
            item.setQuantity(newQuantity);
            mMarket.updateCart(item);

        } catch (final Exception e) {
            JOptionPane.showMessageDialog(this, "Error: " + e, "Adding to cart", JOptionPane.WARNING_MESSAGE);
        }
    }
}



class CartPanel extends JPanel {
    private static final long   serialVersionUID    = 7199745180760941548L;

    private final JTable        gTable;

    protected final Market      mMarket;

    public CartPanel(final Market pMarket) {
        mMarket = pMarket;

        setLayout(new BorderLayout());
        gTable = new JTable(mMarket.getCartModel());
        add(new JScrollPane(gTable));

        setBorder(new TitledBorder("Shopping Cart"));
    }
}



class ShoppingCartTableModel extends AbstractTableModel {
    private static final long   serialVersionUID    = 1536498413051546662L;

    private final HashSet<Item> mShoppingCart;

    public ShoppingCartTableModel(final HashSet<Item> pShoppingCart) {
        mShoppingCart = pShoppingCart;
    }

    @Override public Object getValueAt(final int pRowIndex, final int pColumnIndex) {
        try {
            final Item item = (Item) mShoppingCart.toArray()[pRowIndex];
            switch (pColumnIndex) {
                case 0:
                    return item.mName;
                case 1:
                    return new Float((float) item.mPriceCents / 100);
                case 2:
                    return Integer.valueOf(item.getQuantity());
                default:
                    System.out.println("CartPanel.CartPanel(...).new AbstractTableModel() {...}.getValueAt()");
                    throw new IllegalStateException("Bad index! Wrong amount of columns!");
            }
        } catch (final Exception e) {
            e.printStackTrace();
            return "[]";
        }
    }
    @Override public String getColumnName(final int pColumnIndex) {
        switch (pColumnIndex) {
            case 0:
                return "Name";
            case 1:
                return "Price";
            case 2:
                return "Quantity";
            default:
                System.out.println("CartPanel.CartPanel(...).new AbstractTableModel() {...}.getColumnName()");
                throw new IllegalStateException("Bad index! Wrong amount of columns!");
        }
    }
    @Override public int getRowCount() {
        if (mShoppingCart == null) return 0;
        return mShoppingCart.size();
    }
    @Override public int getColumnCount() {
        return 3;
    }
}



class MarketGUI extends JFrame {
    private static final long   serialVersionUID    = 65473329699793884L;

    private final Market        mMarket;

    public MarketGUI(final Market pMarket) {
        mMarket = pMarket;

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setTitle("Da Thrift Shop");
        setLayout(new BorderLayout());

        add(new OrderPanel(mMarket), BorderLayout.WEST);
        add(new CartPanel(mMarket), BorderLayout.CENTER);

        setBounds(100, 100, 800, 600);
        setVisible(true);
    }
}



public class Market {
    public static void main(final String[] args) {
        final Market m = new Market();
        new MarketGUI(m);
    }

    private final ArrayList<Item>           mStock          = new ArrayList<>();
    private final HashSet<Item>             mShoppingCart   = new HashSet<>();
    private final ArrayListModel<Item>      mStockModel;
    private final ShoppingCartTableModel    mCartModel;

    public Market() {
        mStock.add(new Item("Bath towel", 550));
        mStock.add(new Item("Plebney light", 2000));
        mStock.add(new Item("Gorilla suit", 3000));
        mStock.add(new Item("Whizz games console", 5500));
        mStock.add(new Item("Oven", 20000));

        mStockModel = new ArrayListModel<>(mStock);
        mStockModel.fireDataChangedEvent();
        mCartModel = new ShoppingCartTableModel(mShoppingCart);
    }

    public void updateCart(final Item pItem) {
        if (pItem.getQuantity() < 1) mShoppingCart.remove(pItem);
        else mShoppingCart.add(pItem);
        mCartModel.fireTableDataChanged();
    }
    public ArrayList<Item> getStock() {
        return mStock;
    }
    public HashSet<Item> getShoppingCart() {
        return mShoppingCart;
    }

    public ArrayListModel<Item> getStockModel() {
        return mStockModel;
    }
    public ShoppingCartTableModel getCartModel() {
        return mCartModel;
    }

}