How to avoid firing actionlistener event of JComboBox when an item is get added into it dynamically in java?

后端 未结 9 2285
广开言路
广开言路 2020-12-04 00:23

I need your suggestions and guidence on following task.

I have a frame which has two JComboBoxes supposed they are named combo1 and combo2, a JTable and other compon

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 00:35

    What i do instead of adding and removing action listeners i have a boolean variable in my action listeners that is true if it has to allow the action through or false if it has to block it.

    I then set it to false when i do some changes that will fire off the action listener

    JComboBox test = new JComboBox();
    test.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        if(testActionListenerActive)
        {
          //runn your stuff here
        }
      }
    });
    
    //then when i want to update something where i want to ignore all action evetns:
    testActionListenerActive = false;
    //do stuff here like add 
    
    SwingUtilities.invokeLater(() -> testActionListenerActive = false);
    //and now it is back enabled again
    //The reason behind the invoke later is so that if any event was popped onto the awt queue 
    //it will not be processed and only events that where inserted after the enable 
    //event will get processed.
    

提交回复
热议问题