editable JComboBox

后端 未结 1 1025
孤独总比滥情好
孤独总比滥情好 2021-01-12 08:22

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

相关标签:
1条回答
  • 2021-01-12 09:14

    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); 
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题