JComboBox itemStateChanged event called twice at a time

前端 未结 2 1281
故里飘歌
故里飘歌 2021-01-12 17:31
resultCombo = new JComboBox();
resultCombo.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent ie) {
         sampleText=re         


        
相关标签:
2条回答
  • 2021-01-12 17:54

    JComoboBox ItemListener does get called twice for a single change. Once for SELECTED event and once for DESELECTED event.

    See this tutorial page on how to write an ItemListener.

    Basically what you have to do is

    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            //Do any operations you need to do when an item is selected.
        } else if(e.getStateChange() == ItemEvent.DESELECTED){
            //Do any operations you need to do when an item is de-selected.
        }
    }
    
    0 讨论(0)
  • 2021-01-12 18:06

    Based on the documentation of ItemListener

    Invoked when an item has been selected or deselected by the user. The code written for this method performs the operations that need to occur when an item is selected (or deselected).

    This suggested that you will receive an event when an item is deselected or selected. Seen as a change in the selected item in the combo box requires that the currently selected item has to be deselected first, it stands to reason that you will receive a ItemEvent.DESELECTED and ItemEvent.SELECTED event

    0 讨论(0)
提交回复
热议问题