java 可编辑的 JComboBox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6395164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:43:51  来源:igfitidea点击:

editable JComboBox

javaswingjcombobox

提问by Arsen

I have editable JComboBoxand wish to add values to it from its input,e.s when I typing something in JComboBoxand press enter I want that text appear in JComboBoxlist :

我可以编辑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);
    }
}

unfortunately when I press enter two values were inserted instead of one.

不幸的是,当我按 Enter 时,插入了两个值而不是一个。

Why?

为什么?

回答by vehk

From the APIfor JComboBox:

APIJComboBox

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 将收到一个 ActionEvent。如果组合框是可编辑的,则在编辑停止时将触发 ActionEvent。

Thus, your ActionListeneris called two times.

因此,您ActionListener被称为两次。

To only add the item to the JComboBoxwhen edited, you can check for the correct ActionCommandlike this :

要仅将项目添加到JComboBox编辑时,您可以ActionCommand像这样检查是否正确:

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("comboBoxEdited")) {
    //code
    }
}

edit ( -> event dispatch thread)

编辑(-> 事件调度线程)

As already mentioned by trashgod, you should also create and show your frame only in the event dispatch thread :

正如trashgod已经提到的,您还应该仅在事件调度线程中创建和显示您的框架:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Program().setVisible(true); 
        }
    });
}