Vector comboBoxItems = new Vector(); DefaultComboBoxModel model; // ComboBox Items have gotten from Data Base initially. model = new DefaultComboBoxModel(ComboBoxItems); JComboBox Box = new JComboBox(model);
我将此组合框添加到面板.如果我直接在数据库中添加一些项目,那么我希望在组合框中显示新添加的项目.
当我调试时,我可以看到comboBoxItem中的值,但这些值不会出现在我的组合框中.
解决方法
如何使用ComboBoxModel?这样的东西….
JFrame frame = new JFrame("Combo Box Demo"); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200,200); frame.setLayout(new FlowLayout()); Vector comboBoxItems=new Vector(); comboBoxItems.add("A"); comboBoxItems.add("B"); comboBoxItems.add("C"); comboBoxItems.add("D"); comboBoxItems.add("E"); final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems); JComboBox comboBox = new JComboBox(model); frame.add(comboBox); JButton button = new JButton("Add new element in combo Box"); frame.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { model.addElement("F"); } }); frame.setVisible(true);