java - JComboBox 未从 Hashtable 和 ArrayList 填充

标签 java swing arraylist hashtable jcombobox

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

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);
}
}

没有报告错误消息。

最佳答案

My JComboBox subComboBox will populate if I use an String[] rather than ArrayList.

默认的 ComboBoxModel 不支持 ArrayList。

您可以使用 vector 。

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

关于java - JComboBox 未从 Hashtable 和 ArrayList 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15902597/

相关文章:

java - CellEditorListener 不会检测单元格何时被编辑

java - 不允许多次按下按钮

java - 如何向此代码添加按钮?我不知道如何或在哪里放置它

java - 如何修复 : java. lang.ClassCastException : java. util.ArrayList 无法转换为 java.lang.Integer

java - 将整数输入数组列表

javax.naming.NameNotFoundException : Name is not bound in this Context. 无法找到

java - Maven 错误 : Could not find or load main class org. codehaus.plexus.classworlds.launcher.Launcher

java - 如何确定 Java Webstart 应用程序运行测试还是生产?

java - 根据操作系统更改 LaF

java - Arraylist 将最后一个元素读取为倒数第二个元素