Java robot press at

Что такое класс роботов в Java?

Класс роботов в Java был представлен как функция в JDK 1.3. Его можно использовать для запуска событий ввода, таких как движение мыши, щелчок мыши, нажатие клавиш и т. д.

Что такое класс роботов в Java?

Класс Java.awt.Robot используется для управления клавиатурой и мышью и выполнения различных типов операций, связанных с мышью и клавиатурой, с помощью кода Java. Класс Robot обычно используется для автоматизации тестирования.

Реализация класса Java Robot

Приведенный ниже код будет управлять клавиатурой и мышью с помощью класса роботов.

import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.*; public class robotic < public static void main(String[] args) throws IOException, AWTException, InterruptedException < String command = "wordpad.exe"; Runtime run = Runtime.getRuntime(); run.exec(command); try < Thread.sleep(3000); >catch (InterruptedException e) < e.printStackTrace(); >// Create an instance of Robot class Robot myrobot = new Robot(); // keypress will make the virtual keyboard press the parsed keys with a time gap of 300 sec myrobot.keyPress(KeyEvent.VK_L); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_E); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_A); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_R); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_N); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_SPACE); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_W); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_I); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_T); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_H); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_SPACE); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_E); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_D); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_U); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_R); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_E); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_K); Thread.sleep(300); myrobot.keyPress(KeyEvent.VK_A); Thread.sleep(300); > >

Источник

Читайте также:  Shop equipments css v34

Java robot key press, mouse move and click

In this post tested with Java 8(this scripts are good for automations and testing purposes):

  • Mouse Left, Middle and Right click
  • Mouse move to coordinates — x and y with Java robot
  • Robot — mouse double click
  • Java robot type string — simulate user typing/input
    • Java Robot press enter
    • Java Robot press tab
    • Java Robot Copy CTRL + C
    • Java Robot Paste CTRL + V
    • Java Robot Paste text string

    Java has several ways to simulate user inputs. Most popular is by using:

    No additional dependencies or libraries are required. It is very useful when you want to test desktop or even web application. You can simulated user behavior by using this simple methods.

    Mouse Left, Middle and Right click

    Select mouse button and press it several times:

    public static void clickMouse(String button,Robot r, int number) < int mouse; switch (button) < case "left": mouse = InputEvent.BUTTON1_MASK;break; case "right": mouse = InputEvent.BUTTON3_MASK;break; case "middle": mouse = InputEvent.BUTTON2_MASK;break; default: mouse = InputEvent.BUTTON1_MASK;break; >for(int i =0;i > 

    Java Robot move mouse at coordinates

    Move the mouse pointer at specific coordinates in pixels. In this example x — 600 and y — 500.

    ro = new Robot(); moveMouse(ro, 600,500); public static void moveMouse(Robot r, int X, int Y)

    Java Robot mouse double click

    Press mouse left button twice:

    public static void doubleClickMouse(Robot r)

    Java Robot press enter

    Press keyboard enter once:

    public static void pressEnter(Robot r)

    Java Robot press tab

    Press keyboard enter tab once:

    public static void pressTab(Robot r)

    Java Robot Copy CTRL + C

    Simulate copy from keyboard input:

    public static void copy(Robot r)

    Java Robot Paste CTRL + V

    public static void paste(Robot r)

    Java Robot Paste text string

    Paste any given string as simulation of clipboard paste:

    import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; public static void pasteText(String text, Robot r)< StringSelection stringSelection = new StringSelection(text); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, stringSelection); //Paste attached file paste r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_V); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_V); 

    Java Robot Select All CTRL + A

    Select all text by CTRL + A

    public static void selectAll(Robot r) < //Select all r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_A); r.delay(1000); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_A); >

    Java Robot type any letter

    You can simulate typing by this two methods. This one is doing button press and the next one has all letters and special buttons of the keyboard.

    public static void pressButton(Robot r, String button, int number) < for(int i =0;i> public static void type(Robot r, String character) < switch (character) < //letters case "a": r.keyPress(KeyEvent.VK_A); break; case "b": r.keyPress(KeyEvent.VK_B); break; case "c": r.keyPress(KeyEvent.VK_C); break; case "d": r.keyPress(KeyEvent.VK_D); break; case "e": r.keyPress(KeyEvent.VK_E); break; case "f": r.keyPress(KeyEvent.VK_F); break; case "g": r.keyPress(KeyEvent.VK_G); break; case "h": r.keyPress(KeyEvent.VK_H); break; case "i": r.keyPress(KeyEvent.VK_I); break; case "j": r.keyPress(KeyEvent.VK_J); break; case "k": r.keyPress(KeyEvent.VK_K); break; case "l": r.keyPress(KeyEvent.VK_L); break; case "m": r.keyPress(KeyEvent.VK_M); break; case "n": r.keyPress(KeyEvent.VK_N); break; case "o": r.keyPress(KeyEvent.VK_O); break; case "p": r.keyPress(KeyEvent.VK_P); break; case "q": r.keyPress(KeyEvent.VK_Q); break; case "r": r.keyPress(KeyEvent.VK_R); break; case "s": r.keyPress(KeyEvent.VK_S); break; case "t": r.keyPress(KeyEvent.VK_T); break; case "u": r.keyPress(KeyEvent.VK_U); break; case "v": r.keyPress(KeyEvent.VK_V); break; case "w": r.keyPress(KeyEvent.VK_W); break; case "x": r.keyPress(KeyEvent.VK_X); break; case "y": r.keyPress(KeyEvent.VK_Y); break; case "z": r.keyPress(KeyEvent.VK_Z); break; //special case "alt": r.keyPress(KeyEvent.VK_ALT); break; case "tab": r.keyPress(KeyEvent.VK_TAB); break; case "enter": r.keyPress(KeyEvent.VK_ENTER); break; case "shift": r.keyPress(KeyEvent.VK_SHIFT); break; case "windows": r.keyPress(KeyEvent.VK_WINDOWS); break; case "control": r.keyPress(KeyEvent.VK_CONTROL); break; case "open_bracket": r.keyPress(KeyEvent.VK_OPEN_BRACKET); break;//[ case "escape": r.keyPress(KeyEvent.VK_ESCAPE); break;//[ default: throw new IllegalArgumentException("Cannot type character " + character); >> 

    Java Robot the code

    Class which shows the usages of this methods. This will help you to automate your tests by key pressing, mouse clicks and moves. Feel free to comment below:

    package robot; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; public class RobotTest < public static void main(String[] args) < Robot ro; < try < ro = new Robot(); moveMouse(ro, 600,500); doubleClickMouse(ro); clickMouse("right", ro, 1); pressEnter(ro); >catch (AWTException e) < e.printStackTrace(); >> > // // Move mouse at coordinates // public static void moveMouse(Robot r, int X, int Y) < r.mouseMove(X, Y); >// // Click mouse button twice // public static void doubleClickMouse(Robot r) < r.mousePress(InputEvent.BUTTON1_MASK); r.mouseRelease(InputEvent.BUTTON1_MASK); r.delay(1000); r.mousePress(InputEvent.BUTTON1_MASK); r.mouseRelease(InputEvent.BUTTON1_MASK); >// // Click mouse buttons n - times // public static void clickMouse(String button,Robot r, int number) < int mouse; switch (button) < case "left": mouse = InputEvent.BUTTON1_MASK;break; case "right": mouse = InputEvent.BUTTON3_MASK;break; case "middle": mouse = InputEvent.BUTTON2_MASK;break; default: mouse = InputEvent.BUTTON1_MASK;break; >for(int i =0;i > // // Press Enter // public static void pressEnter(Robot r) < r.delay(1000); r.keyPress(KeyEvent.VK_ENTER); r.delay(1000); >// // Press Tab // public static void pressTab(Robot r) < r.delay(1000); r.keyPress(KeyEvent.VK_TAB); r.delay(1000); >// // Copy CTRL + C // public static void copy(Robot r) < r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_C); r.delay(1000); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_C); >// // Paste CTRL + V // public static void paste(Robot r) < r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_V); r.delay(1000); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_V); >// // Paste CTRL + V // public static void pasteText(String text, Robot r) < StringSelection stringSelection = new StringSelection(text); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, stringSelection); //Paste attached file paste r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_V); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_V); >// // Select All CTRL + A // public static void selectAll(Robot r) < //Select all r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_A); r.delay(1000); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_A); >// // Select press buttons // public static void pressButton(Robot r, String button, int number) < for(int i =0;i> public static void type(Robot r, String character) < switch (character) < //letters case "a": r.keyPress(KeyEvent.VK_A); break; case "b": r.keyPress(KeyEvent.VK_B); break; case "c": r.keyPress(KeyEvent.VK_C); break; case "d": r.keyPress(KeyEvent.VK_D); break; case "e": r.keyPress(KeyEvent.VK_E); break; case "f": r.keyPress(KeyEvent.VK_F); break; case "g": r.keyPress(KeyEvent.VK_G); break; case "h": r.keyPress(KeyEvent.VK_H); break; case "i": r.keyPress(KeyEvent.VK_I); break; case "j": r.keyPress(KeyEvent.VK_J); break; case "k": r.keyPress(KeyEvent.VK_K); break; case "l": r.keyPress(KeyEvent.VK_L); break; case "m": r.keyPress(KeyEvent.VK_M); break; case "n": r.keyPress(KeyEvent.VK_N); break; case "o": r.keyPress(KeyEvent.VK_O); break; case "p": r.keyPress(KeyEvent.VK_P); break; case "q": r.keyPress(KeyEvent.VK_Q); break; case "r": r.keyPress(KeyEvent.VK_R); break; case "s": r.keyPress(KeyEvent.VK_S); break; case "t": r.keyPress(KeyEvent.VK_T); break; case "u": r.keyPress(KeyEvent.VK_U); break; case "v": r.keyPress(KeyEvent.VK_V); break; case "w": r.keyPress(KeyEvent.VK_W); break; case "x": r.keyPress(KeyEvent.VK_X); break; case "y": r.keyPress(KeyEvent.VK_Y); break; case "z": r.keyPress(KeyEvent.VK_Z); break; //special case "alt": r.keyPress(KeyEvent.VK_ALT); break; case "tab": r.keyPress(KeyEvent.VK_TAB); break; case "enter": r.keyPress(KeyEvent.VK_ENTER); break; case "shift": r.keyPress(KeyEvent.VK_SHIFT); break; case "windows": r.keyPress(KeyEvent.VK_WINDOWS); break; case "control": r.keyPress(KeyEvent.VK_CONTROL); break; case "open_bracket": r.keyPress(KeyEvent.VK_OPEN_BRACKET); break;//[ case "escape": r.keyPress(KeyEvent.VK_ESCAPE); break;//[ default: throw new IllegalArgumentException("Cannot type character " + character); >> > 

    By using SoftHints - Python, Linux, Pandas , you agree to our Cookie Policy.

    Источник

    Robot Class Keyboard Events

    Virender Singh

    Enroll in Selenium Training

    In this tutorial, we are going to cover some of the Robot Class Keyboard Events.

    As discussed in the Robot class Introduction tutorial, the Robot class provides methods that can be used to simulate keyboard and mouse actions, e.g., simulation on OS popups/alerts and even on OS applications like Calculator, Notepad, etc.

    Keyboard methods in Robot class

    To simulate keyboard actions, following Robot class methods should be used :

    Keyboard methods:

    • keyPress(int keycode): This method presses a given key. The parameter keycode is an integer value for the key pressed. For example, to press a key for alphabet A, the value that has to pass is KeyEvent.VK_A i.e., keyPress(KeyEvent.VK_A).
      • KeyEvent is generally a low-level event. In Java AWT, low-level events are events that indicate direct communication from the user like a keypress, key release or a mouse click, drag, move, or release, etc. KeyEvent indicates an event that occurs on pressing, releasing, or typing a key on the component object like a text field.
      • This KeyEvent class has various constant fields like VK_0, VK_1 till VK_9 of type integer. These values are the same as ASCII code for numbers '0' till '9'. Similarly, for alphabets, this class has constant fields like VK_A, VK_B till VK_Z. It also has constant fields for representing special characters like VK_DOLLAR for "$" key, modifier keys like VK_SHIFT for Shift key, etc.

      Practice Exercise to Perform Keyboard events using java Robot Class in Selenium

      Let’s discuss an example from an already available demo page on Toolsqa as “https://demoqa.com/keyboard-events/“.

      Robot Class Keyboard Events

      Here, to Upload any file, select the file first from Open popup which is Desktop Windows popup. Which, in turn, requires the filename to enter, e.g., D1.txt in this example.

      Let's understand how to use the Robot class method to enter a filename.

      If a user needs to enter "D1.txt" in a textbox on a Webpage, he/she can use the sendKeys method, and just a single method call sendKeys("D1.txt") will suffice the purpose. But, to enter text in Desktop Windows popup using keyPress() method, the method needs to be invoked for each character of the input string, like keyPress(KeyEvent.VK_D), keyPress(KeyEvent.VK_1), etc.

      Let us automate the following scenario :

      1. Launch the web browser and launch our practice page https://demoqa.com/keyboard-events/
      2. Click on ‘Click here to browse’ button
      3. Press Shift Key
      4. Enter d to type it as D as the modifier Shift key press
      5. Release Shift Key
      6. Enter remaining part of the file name, i.e., 1.txt to display it as D1.txt
      7. Press Enter key
      8. Click on the Upload button and close the alert
      9. Close the browser to end the program

      Prerequisite: Create a file C:\demo\D1.txt

      Following is the sample code:

      package com.toolsqa.tutorials.actions; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.IOException; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class RobotKeyboardDemo < public static void main(String[] args) throws InterruptedException, AWTException, IOException < System.setProperty("webdriver.gecko.driver","C:\\Selenium\\lib\\geckodriver-v0.24.0-win64\\geckodriver.exe"); // Create a new instance of the Firefox driver WebDriver driver = new FirefoxDriver(); String URL = "https://demoqa.com/keyboard-events/"; //Start Browser driver.get(URL); //maximize browser driver.manage().window().maximize(); Thread.sleep(2000); // This will click on Browse button WebElement webElement = driver.findElement(By.id("browseFile")); //click Browse button webElement.sendKeys(Keys.ENTER); //Create object of Robot class Robot robot = new Robot(); //Code to Enter D1.txt //Press Shify key robot.keyPress(KeyEvent.VK_SHIFT); //Press d , it gets typed as upper case D as Shift key is pressed robot.keyPress(KeyEvent.VK_D); //Release SHIFT key to release upper case effect robot.keyRelease(KeyEvent.VK_SHIFT); robot.keyPress(KeyEvent.VK_1); robot.keyPress(KeyEvent.VK_PERIOD); robot.keyPress(KeyEvent.VK_T); robot.keyPress(KeyEvent.VK_X); robot.keyPress(KeyEvent.VK_T); //Press ENTER to close the popup robot.keyPress(KeyEvent.VK_ENTER); //Wait for 1 sec Thread.sleep(1000); //This is just a verification part, accept alert webElement = driver.findElement(By.id("uploadButton")); webElement.click(); WebDriverWait wait = new WebDriverWait(driver, 10); Alert myAlert = wait.until(ExpectedConditions.alertIsPresent()); //Accept the Alert myAlert.accept(); //Close the main window driver.close(); > > 

      Note: Even though Robot class specifies to follow keyRelease for each keyPress event, Alphabets and numbers don't have any side effects on the next statements. Therefore, generally, users skip the keyRelease event for Alphabets and numbers. On the other hand, all the modifier keys such as SHIFT, ALT, etc. will always have a side effect on the next statements. As a result, it is still mandatory to specify keyRelease for each keyPress event of the modifier keys.

      Just Try commenting out robot.keyRelease(KeyEvent.VK_SHIFT); in the above sample code and run the script. You will notice the file name types as, 'D!.TXT'. It is because the key pressed effect for the SHIFT key gets carried forward to the next typed text and types it in the uppercase.

      Summary

      To conclude, in this tutorial, we have covered Robot keyboard methods used to interact with operating system specific popup or applications in Selenium script.

      • keyPress(int keycode): Method to press a given key.
      • keyRelease(int keycode): Method to release a given key.

      As already briefed in the Robot introduction tutorial, the Robot class also provides methods to simulate mouse actions. We will cover those methods in detail in the next tutorial, i.e., Robot Class Mouse Events.

      Источник

Оцените статью