我正在创建一个Fruit和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);
}
}
未报告任何错误消息。
答案 0 :(得分:1)
如果我使用String []而不是ArrayList,我的JComboBox subComboBox将填充。
默认的ComboBoxModel不支持ArrayList。
您可以使用Vector。
如果您确实想使用ArrayList,则需要创建自定义模型。或者创建一个循环,一次将ArrayList中的项添加到模型中。创建自定义模型并不难,只需复制DefaultComboBoxModel的代码并将代码更改为使用List而不是Vector。