如何防止多次点击JComboBox

时间:2014-07-25 11:17:48

标签: java swing listener jcombobox

我尝试实现一种机制,它会在JComboBox上多次点击(我使用popupListeners)之前阻止,并为该事件监听器执行包含。

例如:

public class SomeClass{

 protected boolean semaphore = false;

 public void initComboBox() {

 JComboBox targetControllersComboBox = new JComboBox(); // combobox object
 targetControllersComboBox.addPopupMenuListener(new PopupMenuListener() {

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent event) {

            if (semaphore == false) {
                semaphore = true; // here acquired semaphor 

                // HERE SOME CODE //

                semaphore = false; // here release semaphor 
            }

         }
   }

}

我想在执行popupListener之前已经运行代码之前避免在popupListener中运行代码。当popUplistener完成工作时,用户可以执行下一个popUplistener。不幸的是,我的例子并没有阻止这种情况。有人可以帮忙吗?我会很乐意帮忙。

更新:跟随(maris)重新发生问题:

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent event) {

                JComboBox comboBox = (JComboBox) event.getSource();
                comboBox.removePopupMenuListener(this);

                // some code ....
                // now Listener is disabled and user cant execute next listener until this listener not stop working


                comboBox.addPopupMenuListener(this); // after some code we add again listener, user now can use again listener

         }

1 个答案:

答案 0 :(得分:1)

一般来说,为避免在事件处理过程中发生重复事件,我们可以按照以下步骤操作:

  1. 使用小部件添加事件监听器
  2. 触发事件后,请在事件处理乞讨时删除事件侦听器
  3. 事件处理(业务逻辑)结束后,添加事件监听器
  4. 我给出了JButton的骨架示例供您参考。

    例如:

    JButton submit = new JButton(...)
    submit.addActionListener(this);
    ...
    
    public void actionEvent(...) {
        // on submit clicked
        submit.removeActionListener();
        // do the business logic
        submit.addActionListener(this);
    }
    

    希望这会对你有所帮助。

    此致

    Maris的

相关问题