2014-07-25 31 views
2

我嘗試實現一種機制,該操作會在JComboBox之前多次點擊(我使用popupListeners)並且執行包含該事件偵聽器之前阻止該機制。如何防止在JComboBox上多次點擊

例如:

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。不幸的是,我的例子並沒有預防這種情況。任何人都可以幫忙我會很滿意的幫助。

UPDATE:按照(馬里斯)RESLOVE問題:

 @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 

     } 
+2

Swing是單線程軟件,因此用戶無法在同一時間運行兩個偵聽器。你想在你的GUI(而不是在你的代碼)中實現什麼? –

回答

1

一般來說,以避免重複事件的事件過程中的處理,我們可以按照下面的步驟射擊:

  1. 添加事件監聽小部件
  2. 一旦事件被觸發,在事件處理開始時移除事件偵聽器
  3. 一旦事件處理(業務邏輯)爲o ver,添加事件監聽器

我給了JButton的骨架示例供您參考。

如:

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

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

希望這會幫助你。

問候,

馬里斯

+0

謝謝!你的代碼幫助! –

相關問題