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