This is a little mouse hook application that I wrote a few years ago and I just was wondering why it makes my mouse lag whenever I run it.
I remember reading somewhere t
You are requesting the mouse position at a very fast rate. Try adding a Thread.sleep(time) in your loop:
while (true){
j.setText("Current Mouse Location: " + m.printLocation());
c.setText(String.valueOf(m.getMouseColor()));
// waiting a few milliseconds
Thread.sleep(200);
}
Also, it's best practice to reuse objects to avoid reallocation.
You could improve your method getMouseColor
like this:
// Global var
Robot robot;
MouseLocation() throws AWTException {
robot = new Robot();
}
public Color getMouseColor() {
return robot.getPixelColor(x, y);
}
EDIT:
Following the suggestion by @cricket_007, use a timer to avoid using a Thread.sleep in the main thread (and inside a while-loop):
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