如何在mouseEvent中不断检查鼠标左键单击是否被按住

  • 本文关键字:单击 是否 鼠标 mouseEvent java
  • 更新时间 :
  • 英文 :

static boolean enabled = false; 
@Override
public void mousePressed(MouseEvent e) {
enabled = true;
if (e.getButton() == 1) {
try {
do  {

while (enabled) {
System.out.println("registered click");
Thread.sleep(1000);

}
} while (e.isMetaDown());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(frame, "not working");
}
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("released");
enabled = !enabled;
}

即使我松开鼠标,如果我添加一个中断,它也会继续循环;在那里,它只会停止while循环,而不会继续检查条件。请问我如何在while循环中不断检查条件?

编辑:好吧,我使用Swing作为框架,我试图实现的是,当我单击鼠标左键时,循环开始并在按住鼠标左键的同时继续,但当我抬起手指并释放鼠标按钮时,循环停止,但它不会停止循环。即使我松开鼠标,它也会继续循环。

问题是不能在这里启动无限循环,因为第一个事件一发生就会导致死锁。您只需要等待函数被调用,然后相应地更新状态。然后,您可以在程序的其他地方阅读并对该州采取行动。由于事件与程序的其他部分在一个单独的线程中,因此可以在主线程中创建循环或生成一个新线程。

附带说明一下,您不需要在此处检查异常。MouseEvent只存储有关事件的信息。创建后,它被创建,它不会被更改。

static boolean enabled = false;
@Override
public void mousePressed(MouseEvent e) {
// Ignore events if they are not for the button we care about
if (e.getButton() == 1) {
enabled = true;
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == 1) {
enabled = false;
}
}
// In some other thread (such as the one which created the JPanel)
while (true) {
if (enabled) {
System.out.println("registered click");
Thread.sleep(1000);
}
}

最新更新