java语言鼠标移动的实现有很多方法,这里是一种简单实用方法。鼠标移动实现:鼠标移动是相对移动,即相对鼠标当前的位置而做的移动。



 

java语言鼠标移动的实现有很多方法,这里是一种简单实用方法。

鼠标移动实现:鼠标移动是相对移动,即相对鼠标当前的位置而做的移动。这里我们需要获取鼠标当前位置的坐标,可以通过java.awt.MouseInfo类来获取鼠标信息,然后用java.awt.robot来实现鼠标位置的移动。

代码见下:



1 import java.awt.Dimension;
2 import java.awt.Robot;
3 import java.awt.Point;
4 import java.awt.Toolkit;
5 import java.awt.MouseInfo;
6 import java.awt.AWTException;
7 import java.awt.event.InputEvent;
8 import javax.swing.*;
9
10 public class MyMouseController{
11
12     private Dimension dim; //存储屏幕尺寸
13     private Robot robot;//自动化对象
14
15     public MyMouseController(){
16         dim = Toolkit.getDefaultToolkit().getScreenSize();
17         System.out.println("屏幕大小为:" + dim.getWidth() + " " + dim.getHeight());
18         try{
19             robot = new Robot();
20         }catch(AWTException e){
21             e.printStackTrace();
22         }
23     }
24
25     public void Move(int width,int heigh){    //鼠标移动函数
26         System.out.println("enter Move()...");
27         Point mousepoint = MouseInfo.getPointerInfo().getLocation();
28           System.out.println("移动前坐标:" + mousepoint.x + " " + mousepoint.y);
29           width += mousepoint.x;
30           heigh += mousepoint.y;
31         try{
32             robot.delay(3000);
33             robot.mouseMove(width,heigh);
34         }catch(Exception e){
35             e.printStackTrace();
36         }
37         System.out.println("移动后坐标:" + width + " " + heigh);
38         //robot.mousePress(InputEvent.BUTTON1_MASK);//鼠标单击
39     }
40
41
42     public static void main(String args[])throws Exception{
43
44
45
46         MyMouseController mmc = new MyMouseController();
47
48         System.out.println("mouse control start:");
49         mmc.Move(20,20);//坐标为相对坐标
50         System.out.println("=======第二次移动=======");
51         mmc.Move(512,384);
52
53         System.out.println("mouse control stop.");
54
55     }
56 }


本程序实现两次移动 第一次移动相对坐标为(20,20)第二次为(512,384)。