当我运行这个小鼠标钩应用程序时,为什么我的鼠标会滞后?

这是我几年前写的一个小鼠标钩子应用程序,我只是想知道为什么每次运行它都会导致鼠标滞后。

我记得在某处我必须调用一些方法来手动处理资源或者使用MouseListener。 每当我在屏幕上拖动任何窗口时,它都会使鼠标滞后,这不会在它没有运行时发生。 知道为什么吗? (我知道我在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 = px; y = py; 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(时间):

 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的建议,使用计时器以避免在主线程中使用Thread.sleep(并在while循环内):

 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