下面是创建分别具有代号名称、价格和数量的项目的代码。
public class StockData {
private static class Item {
Item(String n, double p, int q) {
name = n;
price = p;
quantity = q;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
private final String name;
private final double price;
private int quantity;
}
public 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;
}
}
}
这是一个不同的类,它是我的 gui 的一部分,如下所示:http: //imgur.com/Jhc4CAz
我的想法是你输入一个项目的代码,例如。22 然后输入您想添加到库存中的数量,例如 5 您单击添加,这样它就会添加到变量中,但会立即更新框中的文本,如您在屏幕上看到的那样。
我真的对 hashmap / list 感到困惑我认为将所有数据从 hashmap 复制到 list 并几乎将其相乘,必须有更好的方法来实现这一点。
public class UpdateStock extends JFrame implements ActionListener {
JTextField stockNo = new JTextField(4);
JButton addButton = new JButton("ADD");
JSpinner quantitySlider = new JSpinner();
JTextArea catalog = new JTextArea(7, 30);
List items = new ArrayList();
public UpdateStock(){
setLayout(new BorderLayout());
setBounds(100, 100, 450, 500);
setTitle("Update Stock");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel top = new JPanel();
add("North", top);
JPanel middle = new JPanel();
add("Center", middle);
top.add(stockNo);
top.add(quantitySlider);
top.add(addButton);
catalog.setLineWrap(true);
catalog.setWrapStyleWord(true);
catalog.setEditable(false);
middle.add(new JScrollPane(catalog));
for(String key : StockData.getStock().keySet()) {
catalog.append("Item: " + key +"\n");
items.add(StockData.getName(key));
catalog.append("Name: " + StockData.getName(key) +
" Price: " + StockData.getPrice(key) +
" Qty: " + StockData.getQuantity(key)+"\n");
}
setResizable(false);
setVisible(true);
}
}