JComboBox没有从哈希表和数组列表中填充



我正在创建一个水果和蔬菜应用程序,允许用户从下拉框中进行选择。如果我使用String[]而不是ArrayList,我的JComboBox subComboBox将被填充。有什么想法或文件可以让我看看吗?对于下面的代码,子combobox 为空。

public class FruitAndVedg extends JFrame implements ActionListener, ItemListener {
private static final long serialVersionUID = 4L;
private JComboBox mainComboBox;
private JComboBox subComboBox;
private ArrayList item;
private Hashtable<ArrayList<Object>, Object> subItems = new Hashtable<>();
public FruitAndVedg() {
    item = new ArrayList();
    item.add("Select Item");
    item.add("Fruit");
    item.add("Vedg");
    mainComboBox = new JComboBox(item.toArray());
    mainComboBox.addActionListener(this);
    mainComboBox.addItemListener(this);
    getContentPane().add(mainComboBox, BorderLayout.WEST);
    subComboBox = new JComboBox();
    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX");
    getContentPane().add(subComboBox, BorderLayout.CENTER);
    String[] subItems1 = {"Select Fruit", "Apple", "Plum"};
    subItems.put(item, subItems1);
    String[] subItems2 = {"Select Vedg", "Carrot", "Peas"};
    subItems.put(item, subItems2);
}
@Override
public void actionPerformed(ActionEvent ae) {
    String item = (String) mainComboBox.getSelectedItem();
    Object o = subItems.get(item);
    if (o == null) {
        subComboBox.setModel(new DefaultComboBoxModel());
    } else {
        subComboBox.setModel(new DefaultComboBoxModel((String[]) o));
    }
}
@Override
public void itemStateChanged(ItemEvent ie) {
    if (ie.getStateChange() == ItemEvent.SELECTED) {
        if (ie.getSource() == mainComboBox) {
            if (mainComboBox.getSelectedIndex() != 0) {
            }
        }
    }
}
  public static void main(String[] args) {
    JFrame frame = new FruitAndVedg();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
}

没有错误消息报告。

如果我使用String[]而不是ArrayList,我的JComboBox subComboBox将被填充。

默认的ComboBoxModel不支持ArrayList。

你可以使用Vector

如果你真的想使用ArrayList,那么你需要创建一个自定义模型。或者创建一个循环,一次一个地将数组列表中的项添加到模型中。创建自定义模型并不难,只需复制DefaultComboBoxModel的代码,并将代码更改为使用List而不是Vector。

最新更新