SoFunction
Updated on 2025-03-08

Java implements mouse simulation and keyboard mapping

This article shares the specific code for Java to implement mouse simulation and keyboard mapping for your reference. The specific content is as follows

Keywords: java mouse simulation keyboard mapping

The Robot class was implemented after Java SDK 1.3. This class is used to generate input events for test automation, self-running demo programs, and other applications that require control of the mouse and keyboard. Robot's main purpose is to facilitate automatic testing on the Java platform.

The difference between using this class to generate input events and sending events to an AWT event queue or an AWT component is that events are generated in the platform's native input queue. For example, the mouse cursor will actually be moved instead of just generating a mouse movement event.

The main mouse and keyboard control methods in Robot are:

• void keyPress(int keycode) Press the given key.
• void keyRelease(int keycode) Release the given key.
• void mouseMove(int x, int y) Move the mouse pointer to the given screen coordinates.
• void mousePress(int buttons) Press one or more mouse buttons.
• void mouseRelease(int buttons) Release one or more mouse buttons.
• void mouseWheel(int wheelAmt) Rotate the scroll wheel on the mouse equipped with the scroll wheel.

Let’s take practical mouse control to implement a simple mouse control program, MouseController. The program function is very simple: randomly move the mouse and click the left button

package robot;

import ;
import ;
import ;
import ;
import ;
import ;

public class MourseControl implements Runnable{
 private Dimension dim;
 private Random rand;
 private Robot robot; 

 private volatile boolean stop = false;
  public MourseControl()
  {
   //
   dim = ().getScreenSize();
   rand = new Random();
   try {
  robot = new Robot();
 } catch (AWTException e) {
  // TODO Auto-generated catch block
  ();
 }
  }
 /**
 * @param args
 */
 public static void main(String[] args) {
 // TODO Auto-generated method stub
    MourseControl m = new MourseControl();
    Thread t = new Thread(m);
    ();
    ("MourseControl start...");
    try {
  (10000);
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  ();
 }
    ();
    ("MourseControl stop...");
 }
 public void run() {
 // TODO Auto-generated method stub
 while(!stop)
 {
  int x = ();
  int y = ();

  try {
  (2000);
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  ();
  }
  (x, y);
  ("move to :x="+x+",y="+y);
  (InputEvent.BUTTON1_MASK);
 }

 }
 public synchronized void stop()
 {
 stop = true;
 }

}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.