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

后端 未结 9 2257
广开言路
广开言路 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:23

    This works:

    /** Implements a Combo Box with special setters to set selected item or
      * index without firing action listener. */
    public class MyComboBox extends JComboBox {
    
    /** Constructs a ComboBox for the given array of items. */
    public MyComboBox(String[] items) {
      super(items);
    }
    
    /** Flag indicating that item was set by program. */
    private boolean isSetByProgram;
    
    /** Do not fire if set by program. */
    protected void fireActionEvent() {
      if (isSetByProgram)
        return;
      super.fireActionEvent();
    }
    
    /** Sets selected Object item without firing Action Event. */
    public void setSelection(Object item) {
      isSetByProgram = true;
      setSelectedItem(item);
      isSetByProgram = false;
    }
    
    /** Sets selected index without firing Action Event. */
    public void setSelection(int index) {
      isSetByProgram = true;
      setSelectedIndex(index);
      isSetByProgram = false;
    }
    
    }
    

    Note: You can't just override setSelectedItem(...) or setSelectedIndex(...) because these are also used internally when items are actually selected by user keyboard or mouse actions, when you do not want to inhibit firing the listeners.

提交回复
热议问题