【问题标题】:Why is my mouse lagging when I run this small mouse hook application?当我运行这个小鼠标钩子应用程序时,为什么我的鼠标滞后?
【发布时间】: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()));
        }
    }
}

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您正在以非常快的速度请求鼠标位置。 尝试在循环中添加 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 循环中)使用 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
    

    【讨论】:

    • 我建议将其设为自己的线程,而不是让主线程休眠
    • @Zack 感谢您的回答。我认为这是请求+重新分配的速率。由于应用程序中没有其他功能,该线程实际上只会使窗口关闭按钮提前几毫秒响应。
    • 不客气,而且是对的:在我的测试中,“瓶颈”是利率。如果要对获取的值进行一些处理,则应该使用线程。
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多