editable JComboBox

别等时光非礼了梦想. 提交于 2019-12-19 05:59:12

问题


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?


回答1:


From the API for JComboBox :

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.

Thus, your ActionListener is called two times.

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
    }
}

edit ( -> event dispatch thread)

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); 
        }
    });
}


来源:https://stackoverflow.com/questions/6395164/editable-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!