如何在java中动态添加项目时,如何避免触发JComboBox的actionlistener事件?

Par*_*nak 4 java swing actionlistener jcombobox

我需要你对以下任务的建议和指导.

我有一个框架有两个JComboBoxes,假设它们被命名为combo1和combo2,一个JTable和其他组件.

在使用上述组件可见框架的初始阶段.combo1组合框中填充了一些值,但在初始阶段没有选择任何值,combo2组合框被禁用,表格为空.

我在combo1和combo2上添加了一个actionListener.combo1中有两种类型的值,假设这些值是type1和type2.

条件1:当我们从Combo1中选择值type1时,将调用actionListener方法combo1,该方法调用combo2保持禁用的方法,并将一些行添加到与combo1中的选定值type1相关的表中.

条件2:当我们从combo1中选择值type2时,将调用actionListener方法combo1,该方法调用一个方法,该方法使combo2填充了与type2相关的一些值并被启用但是没有从combo2中选择任何值,并且在我们选择之前表也应保持为空combo2中的任何值.

每次向combo2添加值时,表都会触发combo2的动作侦听器方法.在combo2的actionListener方法中,它获取了combo2选择的值,但是这里没有选择的combo2值导致NullPointerException.

那么我应该怎么做才能在将值添加到combo2之后才能执行combo2的动作列表器方法.

obj*_*cts 10

您可以在添加新元素之前删除动作侦听器,并在完成后将其添加回来.Swing是单线程的,因此无需担心需要触发侦听器的其他线程.

您的听众可能还可以检查是否选择了某些内容,如果没有,则采取适当的措施.比获得NPE更好.


小智 7

尝试这个:

       indicatorComboBox = new JComboBox() {

        /**
         * Do not fire if set by program.
         */
        protected void fireActionEvent() {
            // if the mouse made the selection -> the comboBox has focus
            if(this.hasFocus())
                super.fireActionEvent();
        }
    };
Run Code Online (Sandbox Code Playgroud)


Lud*_*ger 6

我做的不是添加和删除动作侦听器我在我的动作侦听器中有一个布尔变量,如果必须允许动作通过则为true,如果必须阻止它则为false.

然后,当我做一些将触发动作侦听器的更改时,我将其设置为false

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.
Run Code Online (Sandbox Code Playgroud)