可编辑的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键时,插入的是两个值,而不是一个。 为什么?     
已邀请:
        从
JComboBox
的API中:   做出选择后,ActionListener将收到一个ActionEvent。如果组合框是可编辑的,则在编辑停止时将触发ActionEvent。 因此,您的“ 5”被叫两次。 要仅在编辑时将项目添加到
JComboBox
中,您可以像这样检查正确的
ActionCommand
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals(\"comboBoxEdited\")) {
    //code
    }
}
编辑(->事件分配线程) 正如垃圾桶已经提到的,您还应该仅在事件分发线程中创建并显示框架:
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Program().setVisible(true); 
        }
    });
}
    

要回复问题请先登录注册