Monday, 18 November 2013

Move Mouse Pointer with Arrow Keys in Java

moving mouseYes, you are able to move mouse pointer with arrow keys in Java globally and that is theme of the below program. With the help of this program, the cursor pointer goes up when UP arrow key is pressed, down when down arrow key is pressed.... and press the mouse when enter is pressed. Isn't that cool? Let us take a look at the example below.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MoveCursor extends JFrame
{
Robot r;

    public MoveCursor()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Move Cursor with Keyboard");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // hide the visibility
        setUndecorated(true);
        setOpacity(0f);
        setVisible(true);
       
        // Create Robot object
        try
        {
        r=new Robot();
        }catch(Exception e){}
       
        addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent e)
            {
                // If there occured an exception
                // while creating Robot object, r is null
                // then go back
                if(r==null) return;
               
                // Get global current cursor location
                Point p=MouseInfo.getPointerInfo().getLocation();
               
                switch(e.getKeyCode())
                {
                    case KeyEvent.VK_UP: r.mouseMove(p.x,p.y-1); break;
                    case KeyEvent.VK_DOWN: r.mouseMove(p.x,p.y+1); break;
                    case KeyEvent.VK_LEFT: r.mouseMove(p.x-1,p.y); break;
                    case KeyEvent.VK_RIGHT: r.mouseMove(p.x+1,p.y); break;
                    // left click
                    case KeyEvent.VK_ENTER: r.mousePress(MouseEvent.BUTTON1_MASK); r.mouseRelease(MouseEvent.BUTTON1_MASK);
                }
            }
        });
    }
   
    public static void main(String args[])
    {
        new MoveCursor();
    }
}
MouseInfo.getPointerInfo().getLocation(): This method is present in the PointerInfo class whose object can be obtained by getPointerInfo() method in the MouseInfo class. getLocation() returns the current mouse pointer location which is helpful in moving the cursor with arrow keys.

No comments:

Post a Comment