可编辑的JComboBox
|
我有可编辑的
JComboBox
,并希望从其输入中添加值,例如当我在JComboBox
中键入内容并按Enter时,我希望该文本出现在JComboBox
列表中:
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);
}
}
不幸的是,当我按Enter键时,插入的是两个值,而不是一个。
为什么?
没有找到相关结果
已邀请:
1 个回复
剑哎
的API中: 做出选择后,ActionListener将收到一个ActionEvent。如果组合框是可编辑的,则在编辑停止时将触发ActionEvent。 因此,您的“ 5”被叫两次。 要仅在编辑时将项目添加到
中,您可以像这样检查正确的
:
编辑(->事件分配线程) 正如垃圾桶已经提到的,您还应该仅在事件分发线程中创建并显示框架: