2011-11-19 78 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!"); 
}