【问题标题】:JComboBox not populating from Hashtable and ArrayListJComboBox 未从 Hashtable 和 ArrayList 填充
【发布时间】:2013-03-31 22:07:33
【问题描述】:

我正在创建一个允许用户从下拉框中选择的 Fruit and Vedg 应用程序。如果我使用 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);
}
}

未报告错误消息。

【问题讨论】:

  • Hashtable, Object>,必须将此参数更改为 Hashtable 并为 HashTable 中的所有元素使用(开始)相同的数组类型,这意味着 item =新的 ArrayList();回到 String[],因为剩下的元素都是 String[]
  • 理想情况下,我想将所有 String[] 转换为 ArrayLists。
  • item.add("Vedg"); 旁注:“蔬菜”这个词没有“D”。不要包含一个缩写词。

标签: java swing arraylist hashtable jcombobox


【解决方案1】:

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

默认的 ComboBoxModel 不支持 ArrayList。

您可以使用向量。

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

【讨论】:

    猜你喜欢
    • 2019-08-14
    • 2014-10-02
    • 2014-10-03
    • 2010-11-20
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多