JComboBox - 禁止setSelectedItem调用ItemStageChange

时间:2014-02-04 14:29:00

标签: java actionlistener jcombobox changelistener

我有一个JComboBox,它有一个关联的itemStageChanged方法。 JComboxBox有两种更新方式:

  1. 我致电comboBox.setSelectedItem(...)
  2. 用户通过我的GUI选择comboBox中的项目
  3. 我只想(2)发起一个事件。我应该使用哪种方法(例如actionPerformedchangeListeneritemListener?等)只能捕获(2)而不捕获(1)。目前,{1}和(2)正在调用itemStateChanged(即使使用if语句来检查它是否为ItemEvent.SELECTED

    class ItemChangeListener implements ItemListener{
        @Override
        public void itemStateChanged(ItemEvent event) {
           if (event.getStateChange() == ItemEvent.SELECTED) {
              //gets in here if user selects an item with their mouse 
              //or if setSelectedItem is called
           }
        }       
    }
    

1 个答案:

答案 0 :(得分:-1)

尝试一下:

Boolean flag = false;

class ItemChangeListener implements ItemListener{
    @Override
    public void itemStateChanged(ItemEvent event) {
       // Condition for the desired event
       if (!flag && event.getStateChange() == ItemEvent.SELECTED) {
          Object item = event.getItem();
          // do something with object
       }
    }       
}
[...]
//Add the listener
myComboBox.addItemListener(new ItemChangeListener());
[...]
// Setting the selection
flag = true;
comboBox.setSelectedItem(...)
flag = false;

取自here