gpt4 book ai didi

java - 如何防止多次点击 JComboBox

转载 作者:行者123 更新时间:2023-11-30 11:16:17 24 4
gpt4 key购买 nike

我尝试实现一种机制,该机制将防止在 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. 使用小部件添加事件监听器
  2. 一旦触发事件,在事件处理开始时移除事件监听器
  3. 事件处理(业务逻辑)结束后,添加事件监听器

我给出了一个 JButton 的框架示例供您引用。

例如:

JButton submit = new JButton(...)
submit.addActionListener(this);
...

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

希望对您有所帮助。

问候,

马里斯

关于java - 如何防止多次点击 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24954552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com