Why is my mouse lagging when I run this small mouse hook application?

后端 未结 1 1920
-上瘾入骨i
-上瘾入骨i 2021-01-28 15:32

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

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 16:09

    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
    

    0 讨论(0)
提交回复
热议问题