本文介绍了将项目动态添加到 JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Vector comboBoxItems = new Vector();
DefaultComboBoxModel model;
// ComboBox Items have gotten from Data Base initially.
model = new DefaultComboBoxModel(ComboBoxItems);
JComboBox box = new JComboBox(model);
我将此组合框添加到面板中.如果我直接在数据库中添加一些项目,我希望那些新添加的项目显示在组合框中.
I added this combo box to a panel. If I add some items in the database directly, I want those newly added items shown in the combo box.
我在调试时可以看到 comboBoxItems
中的值,但这些值没有出现在我的组合框中.
I can see the values in comboBoxItems
when I debug, but those values do not appear in my combo box.
如何在不关闭面板的情况下将这些新添加的值放入组合框中?
How can I get those newly added values into the combo box without closing the panel?
推荐答案
如何使用 ComboBoxModel?像这样....
How about using ComboBoxModel? Something like this....
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);
这篇关于将项目动态添加到 JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!