2011-11-19 49 views
2

我想讓一個方法等待,直到ActionEvent方法已經處理完畢再繼續。 例子:Java:等待ActionEvent

public void actionPerformed(ActionEvent evt) { 

    someBoolean = false; 

} 

actionPerformed方法被鏈接到一個文本框我有,當你按Enter鍵觸發的方法。我想要做的是,有一個不同的方法暫停,直到actionPerformed方法發生。 例如:

public void method() { 

    System.out.println("stuff is happening"); 
    //pause here until actionPerformed happens 
    System.out.println("You pressed enter!"); 

} 

有沒有辦法做到這一點?

+0

爲什麼這些花式的體操?爲什麼不簡單地有兩個方法,一個是從構造函數或其他事件中調用的,另一個是從JTextField的ActionListener中調用的? –

+1

它看起來像是在等待用戶在文本字段中輸入數據。那麼爲什麼你不顯示一個JOptionPane來要求用戶輸入數據呢? – camickr

回答

2

CountDownLatch應該這樣做。你想創建一個等待1個信號的鎖存器。

在actionPerformed內部,你想調用countDown()和你只想在await()方法裏面。

-edit- 我假設你已經有適量的線程來處理這種情況。

+1

您發佈的鏈接已過時,以下是CountDownLatch的當前API:http://download.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html –

+2

haha​​ha,謝謝。這是第一個從谷歌回來的人。必須記住在未來將Java 7放入搜索中。 – pimaster

+0

*「必須記住在未來將Java 7放入搜索中。」*您也可以爲此[RFE]投票(http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7090875),所以我們總是可以鏈接到'最新'的JavaDocs(並且鏈接將保持穩定)。 –

1

有很多方法,CountDownLatch就是其中之一。另一種使用可重複使用的信號量的方式。

private Semaphore semaphore = Semaphore(0); 
public void actionPerformed(ActionEvent evt) { 
    semaphore.release(); 
} 
public void method() { 
    System.out.println("stuff is happening"); 
    semaphore.acquire(); 
    System.out.println("You pressed enter!"); 
} 

此外,你應該考慮發生的事情的順序。如果用戶多次輸入一次,則應該多次輸入。同樣,如果在等待方法獲取它之後有可能發生行動事件。你可以這樣做:

private Semaphore semaphore = Semaphore(0); 
public void actionPerformed(ActionEvent evt) { 
    if (semaphore.availablePermits() == 0) // only count one event 
     semaphore.release(); 
} 
public void method() { 
    semaphore.drainPermits(); // reset the semaphore 
    // this stuff possibly enables some control that will enable the event to occur 
    System.out.println("stuff is happening"); 
    semaphore.acquire(); 
    System.out.println("You pressed enter!"); 
}