动态添加项目到JComboBox [英] Dynamically adding items to a JComboBox
本文介绍了动态添加项目到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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文