Search code examples
javaawtrobot

Key Board shortcut for moving mouse cursor (num pad) i.e a,6,2,8... are not working with java robot class


We can use Keyboard shortcut of num pad i.e

4-left 6-right 2-down 8-up 

for scrolling mouse cursor without using mouse.

By enabling

Control Panel\Ease of Access\Ease of Access Center\Make the mouse easier to use

But it is not working with java robot class - it simply prints number i.e 4/6/2/8 on screen.

Any idea what might be the problem?

Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
class MoveCursor 
{
    public static void main(String[] args)
    {
        try {
            Robot r=new Robot();
             r.keyPress(KeyEvent.VK_NUMPAD4);
             r.delay(4000);
             r.keyRelease(KeyEvent.VK_NUMPAD4);
        } catch (AWTException ex) {

Logger.getLogger(MoveCursor.class.getName()).log(Level.SEVERE, null, ex); } } }


Solution

  • The documentation states that the java.awt.Robot (see: https://docs.oracle.com/javase/8/docs/api/java/awt/Robot.html) class "generates inputs in the platforms native input queue".

    MouseKeys don't operate on that same level (they literally just replace keystrokes with mouse movement operations).

    So because MouseKeys don't monitor the native input queue that java.awt.Robot adds to, it can't replace the events with mouse movements.

    So in short the conclusion is you can not combine java.awt.Robot class with mouse keys.


    However, the java.awt.Robot class does offer other functionality you can use for controlling the mouse, namely the the #mouseMove function: https://docs.oracle.com/javase/8/docs/api/java/awt/Robot.html#mouseMove-int-int-