我想让一个方法等到ActionEvent方法处理完毕后再继续。示例:
public void actionPerformed(ActionEvent evt) {
someBoolean = false;
}actionPerformed方法链接到我拥有的一个textField,当您按Enter键时,该方法将被触发。我想做的是,让一个不同的方法暂停,直到actionPerformed方法发生。示例:
public void method() {
System.out.println("stuff is happening");
//pause here until actionPerformed happens
System.out.println("You pressed enter!");
}有没有办法做到这一点?
发布于 2011-11-19 10:48:10
CountDownLatch应该可以做到这一点。你想创建一个等待1个信号的锁存器。
在想要调用countDown()的方法内部,以及想要等待()的“actionPerformed”内部。
-edit-我假设你已经设置了适当数量的线程来处理这种情况。
发布于 2011-11-19 11:02:48
有很多方法,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!");
}此外,您还应该考虑正在发生的事情的顺序。如果用户多次点击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!");
}https://stackoverflow.com/questions/8191476
复制相似问题