可编辑的JComboBox [英] editable JComboBox
问题描述
我有可编辑的 JComboBox
并希望从输入中添加值,当我在 JComboBox
然后按回车我希望该文字出现在 JComboBox
列表中:
I have editable JComboBox
and wish to add values to it from its input,e.s when I typing something in JComboBox
and press enter I want that text appear in JComboBox
list :
public class Program extends JFrame
implements ActionListener {
private JComboBox box;
public static void main(String[] args) {
new Program().setVisible(true);
}
public Program() {
super("Text DEMO");
setSize(300, 300);
setLayout(new FlowLayout());
Container cont = getContentPane();
box = new JComboBox(new String[] { "First", "Second", "..." });
box.setEditable(true);
box.addActionListener(this);
cont.add(box);
}
@Override
public void actionPerformed(ActionEvent e) {
box.removeActionListener(this);
box.insertItemAt(box.getSelectedItem(), 0);
box.addActionListener(this);
}
}
不幸的是,当我按回车键时,插入了两个值,而不是一个。
unfortunately when I press enter two values were inserted instead of one.
为什么?
推荐答案
来自 API for JComboBox
:
ActionListener将在选择时收到ActionEvent已经完成了。如果组合框是可编辑的,则在编辑停止时将触发ActionEvent。
The ActionListener will receive an ActionEvent when a selection has been made. If the combo box is editable, then an ActionEvent will be fired when editing has stopped.
因此,您的 ActionListener
被调用两次。
Thus, your ActionListener
is called two times.
要仅在编辑时将项目添加到 JComboBox
,您可以检查正确的 ActionCommand
是这样的:
To only add the item to the JComboBox
when edited, you can check for the correct ActionCommand
like this :
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
//code
}
}
编辑( - >事件派发线程)
如前所述 trashgod ,您还应该只在事件派发线程中创建和显示您的框架:
As already mentioned by trashgod, you should also create and show your frame only in the event dispatch thread :
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Program().setVisible(true);
}
});
}
这篇关于可编辑的JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!