可编辑的 JComboBox
我有可编辑的 JComboBox
并希望从其输入中向其添加值,例如,当我在 JComboBox
中键入内容并按 Enter 键时,我希望该文本出现在 JComboBox< /code> 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);
}
}
不幸的是,当我按 Enter 时,插入了两个值而不是一个。
为什么?
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.
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 API 用于
JComboBox
:因此,您的
ActionListener
被调用两次。要仅在编辑时将项目添加到
JComboBox
,您可以检查正确的ActionCommand
,如下所示:编辑(-> 事件调度线程)
正如 trashgod 已经提到的,您还应该仅在事件调度线程中创建和显示框架:
From the API for
JComboBox
:Thus, your
ActionListener
is called two times.To only add the item to the
JComboBox
when edited, you can check for the correctActionCommand
like this :edit ( -> event dispatch thread)
As already mentioned by trashgod, you should also create and show your frame only in the event dispatch thread :