editable JComboBox
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?
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);
}
});
}
精彩评论