5

I would like to drag and drop using the Robot class in Java. For some reason the code below isn't working. Is there an alternative to this method?

    public static void main (String args []){
    Robot robot = new Robot ();

    robot.mouseMove(350, 226);
    robot.keyPress(InputEvent.BUTTON1_MASK);
    robot.mouseMove(250, 350);
    robot.keyRelease(InputEvent.BUTTON1_MASK);

}

DNA
  • 42,007
  • 12
  • 107
  • 146
Nyx
  • 1,273
  • 6
  • 19
  • 32
  • How far apart are those two x,y points? - if they are too close together, the system may not register a drag event. – DNA Feb 20 '12 at 20:13
  • The new position is approximately 25px away. Sorry I included some irrelevant objects. I have now edited the code. – Nyx Feb 20 '12 at 21:22

2 Answers2

2

You need to use mousePress() and mouseRelease(), not keyPress() and keyRelease()

DNA
  • 42,007
  • 12
  • 107
  • 146
  • Wow. I cannot believe I overlooked that. What a stupid mistake. Thank you for your help. – Nyx Feb 25 '12 at 20:08
0

This is helps anyone and you:

public static void click(int x , int y,int x2, int y2) throws AWTException, InterruptedException{
    Robot b11 = new Robot();

    b11.mouseMove(x, y);    
    b11.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    Thread.sleep(1000);//There is pause in miliseconds
    b11.mouseMove(x2, y2);
    b11.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

}
Arthur Alunts
  • 115
  • 10