editable JComboBox

☆樱花仙子☆ 提交于 2019-12-01 04:03:23
vehk

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