这是我几年前写的一个小鼠标钩子应用程序,我只是想知道为什么每当我运行它时它都会让我的鼠标滞后。
我记得在某处读到,我必须调用某种方法来手动处理资源或使用鼠标侦听器。每当我在屏幕上拖动任何窗口时,它都会使我的鼠标滞后,而当它不运行时不会发生这种情况。 知道为什么吗?(我知道我在 EDT 上运行一个 while 循环,我的 2 个 JLabel 的变量名称是 J 和 C,起诉我)
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MouseLocation {
Point p;
int x,y;
MouseLocation() throws AWTException {
}
public String printLocation(){
p = MouseInfo.getPointerInfo().getLocation();
x = p.x;
y = p.y;
String location = (x + " - " + y);
return location;
}
public Color getMouseColor() throws AWTException{
Robot r = new Robot();
return r.getPixelColor(x, y);
}
public static void main(String[] args) throws AWTException {
MouseLocation m = new MouseLocation();
JFrame frame = new JFrame("Mouse Location Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450,110);
frame.setLayout(new FlowLayout());
JLabel j = new JLabel();
JLabel c = new JLabel();
j.setFont (j.getFont ().deriveFont (24.0f));
c.setForeground(Color.red);
frame.add(j);
frame.add(c);
frame.setVisible(true);
while (true){
j.setText("Current Mouse Location: " + m.printLocation());
c.setText(String.valueOf(m.getMouseColor()));
}
}
}
您正在以非常快的速度请求鼠标位置。尝试在循环中添加一个 Thread.sleep(time):
while (true){
j.setText("Current Mouse Location: " + m.printLocation());
c.setText(String.valueOf(m.getMouseColor()));
// waiting a few milliseconds
Thread.sleep(200);
}
此外,最佳做法是重用对象以避免重新分配。您可以像这样改进方法getMouseColor
:
// Global var
Robot robot;
MouseLocation() throws AWTException {
robot = new Robot();
}
public Color getMouseColor() {
return robot.getPixelColor(x, y);
}
编辑:
按照@cricket_007的建议,使用计时器以避免在主线程(以及 while-loop 内)使用 Thread.sleep:
new Timer().schedule(new TimerTask() {
@Override
public void run() {
j.setText("Current Mouse Location: " + m.printLocation());
c.setText(String.valueOf(m.getMouseColor()));
}
}, 0, 200); // 200 milliseconds