【发布时间】:2016-03-12 13:16:53
【问题描述】:
这是我几年前编写的一个小鼠标挂钩应用程序,我只是想知道为什么每次运行它都会让我的鼠标滞后。
我记得在某处读到我必须调用一些方法来手动处理资源或使用 MouseListener 进行处理。每当我在屏幕上拖动 any 窗口时,它都会使我的鼠标滞后,并且在它不运行时不会发生这种情况。知道为什么吗? (我知道我在 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()));
}
}
}
【问题讨论】: