Search code examples
javaselenium-webdriverawtrobot

Selenium Webdriver: Robot Class: Unable to enter numbers in text field


I have a text field into which I need to enter numbers and moving focus out of the field the value in the text field will be auto populated. I have used below code which worked earlier. But, now running / debugging below code don't enter number.

Code:

public void dwshortname_and_Contract_number_is_entered() throws Throwable {

    Thread.sleep(5000);

    driver.findElement(By.id("consumerNamenew")).sendKeys("TestUser");

     driver.findElement(By.id("consumerNonew")).sendKeys("");

    Robot robot = new Robot();      
    robot.delay(2000);
    robot.keyPress(KeyEvent.VK_2);
    robot.keyRelease(KeyEvent.VK_2);
    robot.keyPress(KeyEvent.VK_0);
    robot.keyPress(KeyEvent.VK_1);
    robot.keyPress(KeyEvent.VK_2);
    robot.keyRelease(KeyEvent.VK_2);
    robot.keyPress(KeyEvent.VK_2);
    robot.keyRelease(KeyEvent.VK_2);
    robot.keyPress(KeyEvent.VK_6);
    robot.keyPress(KeyEvent.VK_9);
    robot.keyRelease(KeyEvent.VK_9);
    robot.keyPress(KeyEvent.VK_9);
    robot.keyRelease(KeyEvent.VK_9);
    robot.keyPress(KeyEvent.VK_4);
    robot.keyPress(KeyEvent.VK_0);
    robot.keyPress(KeyEvent.VK_TAB);        

 }

Solution

  • There is a difference in usage of "SendKeys" which is builtIn in Selenium webdriver and Robot Class.

    SendKeys():

    This is associated with the driver and the element that the driver is pointing to and hence when you send keys it exactly goes to element and puts in the values (Even though you are debugging using eclipse).

    Robot Class:

    Robot on the other hand has nothing to do with neither the driver nor the element driver is pointing to. All it knows is to generate keyboard events (which in your case is entering numbers). So when you open eclipse and run through the code, it will actually send key board events to the place where cursor is pointing to which is "eclipse".

    Now coming to the issue, you face issues when you try to disturb the execution manually doing some operations. If the whole scripts runs without any manual interaction it should run just fine!

    Hope it helps!