我需要能够调用延迟方法,但在此期间不断检查是否已按下鼠标。到目前为止,这是我的延迟方法的代码:
public void delay()
{
for (int i = 0; i<100;i++)
{
try
{
Thread.sleep(10);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
if (isClicked)
{ClickedDuringDelay = true;
System.out.println("PRESSED");}
}
}
当我在延迟期间点击时,从未打印过PRESSED,我不知道为什么。 这段代码有问题吗?
答案 0 :(得分:0)
您可以将摇摆计时器用于此目的
boolean clicked = false;
javax.swing.Timer timer = new Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (clicked) {
...
}
}
});
答案 1 :(得分:0)
如果我做对了,你需要等待(阻止)直到执行点击...所以为此我会做这样的事情
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BlockUntilCliked {
/** The lock object */
private final Lock lock;
/** Condition to be triggered when a click is performed */
private final Condition clicked;
/** Flag to indicate that the mouse was clicked */
private boolean isClicked;
/**
*
*/
public BlockUntilCliked() {
lock = new ReentrantLock();
clicked = lock.newCondition();
}
/**
* method to be called on a click
*/
public void doClick() {
lock.lock();
try {
this.isClicked = true;
clicked.signal();
} finally {
lock.unlock();
}
}
public void waitForClick() throws InterruptedException {
lock.lockInterruptibly();
try {
// do something before block
// wait until not message was handled
while (!isClicked) {
clicked.await();
}
// do something after
} finally {
lock.unlock();
}
}
/**
* @return Returns <code>false</code> if a timeout occurred or the block was unsuccessful
*/
public boolean waitWithTimeout(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
lock.lockInterruptibly();
try {
boolean timedout = false;
// wait until no click was handled
while (!isClicked) {
if (nanos <= 0) {
timedout = true;
break;
}
nanos = clicked.awaitNanos(nanos);
}
// do something after it timed out
return !timedout;
} finally {
lock.unlock();
}
}
}
通过使用这种方法,只要触发点击,你就会等待......不多也不少(或者操作超时)。
希望有所帮助