我正在创建一个 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);
}
}
未报告错误消息。