Simulate mouse move and key pressing

In this example we are going to see how to simulate mouse moves and key pressing events in a Java Desktop Application. This is a quite cool feature that you can use in many ways in your application. For example you can have an interactive “Help” option that shows the user how to perform a certain activity in your applcation.

In short all you have to do in order to simulate mouse moves and key pressing events is:

  • Create a new Frame and a new TextArea.
  • Create a new Robot component.
  • Use robot.mouseMove(xCoord, yCoord) to move the mouse pointer in the coordinates you wish.
  • Use robot.mousePress(InputEvent.BUTTON1_MASK) to press the key want.
  • Use robot.mouseRelease(InputEvent.BUTTON1_MASK) to release the key.

Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Robot;
import java.awt.TextArea;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

public class SimulateMouseMoveAndKeyPress {

  public static void main(String[] args) {

    try {

	// Create frame with specific title

  Frame frame = new Frame("Example Frame");

  // Create a component to add to the frame; in this case a text area with sample text

  Component textArea = new TextArea();

  // Add the components to the frame; by default, the frame has a border layout

  frame.add(textArea, BorderLayout.CENTER);

  // Show the frame

  int width = 300;

  int height = 300;

  frame.setSize(width, height);


  // These coordinates are screen coordinates

  int xCoord = 50;

  int yCoord = 100;

  // Move the cursor

  Robot robot = new Robot();

  robot.mouseMove(xCoord, yCoord);

  // Simulate a mouse click



  // Simulate a key press











    } catch (AWTException e) {

System.out.println("Low level input control is not allowed " + e.getMessage());



This was an example on how to simulate mouse moves and key pressing events.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button