java光标,如何捕获鼠标光标在Java中?

Ok, Most of you will think it's a duplicate because it's already written everywhere that it's not really doable and the only option is to do a screenshot using awt robot.

But... The issue is that the mouse cursor does not even appear in the picture produced by AWT robot... I tries gnome-screeshots and there I can see the mouse cursor. But from the java screenshot, nothing. The entire picture, but not mouse cursor. It's like it's hidding it before taking the picture. I search for a parameter like setIncludeMouseCursor or anything like that with no luck.

I can capture the mouse location, that's fine. But if I capture just this area, again no cursor.

Any idea how to enforce robot.createScreenCapture to capture also the mouse cursor?

解决方案

You need to use MouseInfo class and use its method static getPointerInfo() to get a Pointer object to represent the position of your cursor on the screen.

Once you have the position, you can use Robot to take a screenshot as a BufferedImage and draw the cursor on it. Simple !

SSCCE

package stack;

import java.awt.AWTException;

import java.awt.GraphicsDevice;

import java.awt.GraphicsEnvironment;

import java.awt.MouseInfo;

import java.awt.PointerInfo;

import java.awt.Rectangle;

import java.awt.Robot;

import java.awt.image.BufferedImage;

import java.io.File;

import javax.imageio.ImageIO;

public class GetMousePointer {

public static void main(String[] args) {

final String USER_HOME = System.getProperty("user.home");

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

int width = gd.getDisplayMode().getWidth();

int height = gd.getDisplayMode().getHeight();

BufferedImage blackSquare = new BufferedImage(50, 50, BufferedImage.TYPE_3BYTE_BGR);

for(int i = 0; i < blackSquare.getHeight(); i++){

for(int j = 0; j < blackSquare.getWidth(); j++){

blackSquare.setRGB(j, i, 128);

}

}

try {

Robot robot = new Robot();

BufferedImage screenshot = robot.createScreenCapture(new Rectangle(0,0,width,height));

PointerInfo pointer = MouseInfo.getPointerInfo();

int x = (int) pointer.getLocation().getX();

int y = (int) pointer.getLocation().getY();

screenshot.getGraphics().drawImage(blackSquare, x, y, null);

ImageIO.write(screenshot, "PNG", new File(USER_HOME, "screenshot.PNG"));

} catch (Exception e) {

e.printStackTrace();

}

}

}

Output

hVqW0.png

The top-left corner of the blue square is the position of my cursor.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值