我有两个类,一个包含两个组合框的 gui 类和一个侦听两个组合框的侦听器类。该软件是关于比萨的,组合框是选择比萨的类型和数量,我将发布相关代码。
(gui class)
private Listener listen = new Listener();
private JComboBox chooseItem = new JComboBox();
private JComboBox quantity = new JComboBox();
private String[] selection = {"Choose a Pizza","Margherita", "Pepperoni", "Four Seasons", "Chips", "Garlic Bread", "Potato Wedges", "Cocacola", "Orange Juice", "Lemonade"};
private String[] qSelection = {"0","1","2","3","4","5","6","7","8","9","10"};
private void comboBoxs() {
choosePizza = new JComboBox(selection);
chooseItem.setSelectedIndex(0);
panel.add(choosePizza);
choosPizza.addActionListener(listener);
quantity = new JComboBox(qSelection);
quantity.setSelectedIndex(0);
panel.add(quantity);
quantity.addActionListener(listener);
}
在侦听器类中,我被卡住了,到目前为止还没有找到解决方案。我必须使用 ActionListener,但我不确定如何区分这两个组合框。
(listener class)
public void actionPerformed(ActionEvent event) {
if (actionCommand.equals("Confirm")) {
String q = new String();
String d = new String();
d = description;
q = quantity;
}
else {
JComboBox cbq = (JComboBox)event.getSource();
String itemNumber = (String)cbq.getSelectedItem();
getQuantity(itemNumber);
JComboBox cb = (JComboBox)event.getSource();
String name = (String)cb.getSelectedItem();
getItemName(name);
}
}
public String getItemName(String name) {
description = new String();
description = name;
return name;
}
public String getQuantity(String itemNumber){
quantity = new String();
quantity = itemNumber;
return itemNumber;
}
所以,总结一下:当我在两个 JComboBox 中选择值时,我希望能够将选定的 chooseItem JComboBox 项目存储在“描述”字符串中,并将选定的数量 JComboBox 项目存储在“数量”字符串中。
目前,chooseItem JComboBox 所选项目显示为两个值,并且根本不显示数量。(这实际上是在描述字符串中最后出现的框和数量指向 null 之前的进度。)
我能够在网上找到的所有示例都只涉及带有单个 JComboBox 的 ActionListener,我一直试图让它工作几个小时,但没有运气,我完全陷入困境。