有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取屏幕上任意点的鼠标坐标

每次鼠标在屏幕上的任何位置移动时,我都会尝试获取鼠标的坐标,然后记录坐标,但我对如何操作有点迷茫

目前,我正在尝试使用鼠标侦听器,那么是否可以在整个屏幕上创建一个透明、可点击、可捕获鼠标事件的覆盖

谢谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    将MouseMotionListener与mouseDragged方法一起使用,如:

    public void mouseDragged(MouseEvent e) {
        Graphics g = this.getGraphics();
        int x = e.getX(), y = e.getY(); // you have the coordinates
      // if you want to draw a line for example between 2 mouse pos:
        g.drawLine(lastX,lastY,x,y);
        lastX =x;
        lastY =y;
    }
    
  2. # 2 楼答案

    你需要遵循以下步骤

    步骤:1:implements MouseMotionListener与类的接口

    步骤:2:覆盖它的2-方法

    1. mouseDragged
    2. mouseMoved

    步骤:3:将下面的代码放入mouseMoved(…)

    here, just for explanation purpose i have taken 2-label which will show current mouse's position.

    @Override
        public void mouseMoved(MouseEvent e) {
            String xvalue = new Integer(e.getX()).toString();
            String yvalue = new Integer(e.getY()).toString();
            xlable.setText(xvalue); // here , you can write it into you log
            ylable.setText(yvalue); // here , you can write it into you log
        }
    

    尽我所能,

    enter image description here