有没有一种方法,在 Java 中,不使用事件、监听器等直接检查鼠标按钮之一是否按下?我想要一个线程,每 100 毫秒左右检查一次鼠标按钮是否按下,然后执行某些操作。因此,如果用户按住鼠标按钮一段时间,它将触发多个响应。
所以我正在寻找的是一种无需通过通常的事件处理系统即可提供鼠标状态的方法。
谢谢
最佳答案
我相信这在 Java 中是不可能的。嗯,通过 JNI 是可能的,但这是一个痛苦的世界。
使用事件执行此操作并不难,并且会更好地与您的应用程序的其余部分集成。下面是按下鼠标按钮时每 100 毫秒向控制台写入一次的示例:
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel label = new JLabel("Click on me and hold the mouse button down");
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.getContentPane().add(label);
label.addMouseListener(new TimingMouseAdapter());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class TimingMouseAdapter extends MouseAdapter {
private Timer timer;
public void mousePressed(MouseEvent e) {
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse still pressed...");
}
});
timer.start();
}
public void mouseReleased(MouseEvent e) {
if (timer != null) {
timer.stop();
}
}
}
}
在不同的时间段之后修改它来做不同的事情(比如改变画笔模式)应该是直截了当的。
关于Java 鼠标按下 - 没有事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1372605/