我正在制作一台自动售货机,其中自动售货机内有6个插槽,每个插槽都有自己的苏打水。我们将为苏打水的品牌提供一个enums的arraylist。我已经为每个canslots创建了按钮,但是不知道如何为一个can槽分配一个arraylist值到相应的按钮,以及一旦你点击canslot的按钮减少1直到它为空。
我的实际自动售货机代码在这里:
public class VendingFrame extends JFrame {
private ArrayList<CanSlot> CanSlots = new ArrayList<>();
public VendingFrame() {
CanSlots.add(new CanSlot(Brand.PEPSI));
CanSlots.add(new CanSlot(Brand.COKE));
CanSlots.add(new CanSlot(Brand.SUNKIST));
CanSlots.add(new CanSlot(Brand.DIETPEPSI));
CanSlots.add(new CanSlot(Brand.MTDEW));
CanSlots.add(new CanSlot(Brand.SPRITE));
JPanel panel = new JPanel();
JButton button = new JButton("Pepsi");
button.setPreferredSize(new Dimension(100, 80));
JButton button2 = new JButton("Coke");
button2.setPreferredSize(new Dimension(100, 80));
JButton button3 = new JButton("Diest Pepsi");
button3.setPreferredSize(new Dimension(100, 80));
JButton button4 = new JButton("Sunkist");
button4.setPreferredSize(new Dimension(100, 80));
JButton button5 = new JButton("Mountain Dew");
button5.setPreferredSize(new Dimension(100, 80));
JButton button6 = new JButton("Sprite");
button6.setPreferredSize(new Dimension(100, 80));
JPanel picpanel = new JPanel();
JPanel buttonPanel = new JPanel();
JLabel label = new JLabel();
setLayout(new BorderLayout());
buttonPanel.setLayout(new GridLayout(6, 1));
add(panel);
picpanel.add(label);
label.setIcon(new javax.swing.ImageIcon("C:\\Users\\iacol\\Desktop\\cans.jpg.jpg"));
buttonPanel.add(button);
button.addActionListener(new ClickListener());
buttonPanel.add(button2);
button2.addActionListener(new ClickListener2());
buttonPanel.add(button3);
button3.addActionListener(new ClickListener3());
buttonPanel.add(button4);
button4.addActionListener(new ClickListener4());
buttonPanel.add(button5);
button5.addActionListener(new ClickListener5());
buttonPanel.add(button6);
button6.addActionListener(new ClickListener6());
add(picpanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.EAST);
setSize(700, 700);
setTitle("Vending Machine");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
}
答案 0 :(得分:0)
你可以制作HashMap<Button, List<Product>>();
使用如何识别Button对象并检索值的按钮列表。