Home > database >  Use the java.awt.Robot to write a source Java file
Use the java.awt.Robot to write a source Java file

Time:07-19

I am experimenting to read a Java source file and write it (to Notepad).

But I don't know how to write simbols like: {,},(,),=,;,. ... and operators like ,-,* and so on.

This is the starting point I am using:

private static void writeString(String str) throws Exception {
    // Create instance of Robot class
    Robot robot = new Robot();

    // Press keys using robot
    for (int i = 0; i < str.length(); i  ) {
        try {
            // Check if the current character is a capital letter
            if (Character.isUpperCase(str.charAt(i))) {
                // Press shift key
                robot.keyPress(KeyEvent.VK_SHIFT);
                // Press the current character
                robot.keyPress(Character.toUpperCase(str.charAt(i)));
                // Release shift key
                robot.keyRelease(KeyEvent.VK_SHIFT);
            } else {
                // else display the character as it is
                robot.keyPress(Character.toUpperCase(str.charAt(i)));
            }
        } catch (Exception ignored) {
            // Se ignora
        }

        // wait for 200ms
        sleep(200);
    }

    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
}

CodePudding user response:

TLDR;

You can find all the available VK constants here:

The infamous Robot class Issue

I understand this is a known issue when using the Robot class. I believe there is no reverse lookup for chars to VK keyEvents. (PLEASE! If tell me if someone out there knows a better solution)**

The result usually ends up looking like this:

 public void type(char character) {
  // ... other cases Some more case
  case '=': doType(KeyEvent.VK_EQUALS); break;
  case '~': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_BACK_QUOTE); break;
  case '!': doType(KeyEvent.VK_EXCLAMATION_MARK); break;
  case '@': doType(KeyEvent.VK_AT); break;
  case '#': doType(KeyEvent.VK_NUMBER_SIGN); break;
  case '$': doType(KeyEvent.VK_DOLLAR); break;
  case '%': doType(KeyEvent.VK_SHIFT, KeyEvent.VK_5); break;
  case '^': doType(KeyEvent.VK_CIRCUMFLEX); break;
  case '&': doType(KeyEvent.VK_AMPERSAND); break;
  case '*': doType(KeyEvent.VK_ASTERISK); break;
  case '(': doType(KeyEvent.VK_LEFT_PARENTHESIS); break;
  case ')': doType(KeyEvent.VK_RIGHT_PARENTHESIS); break;
  case '_': doType(KeyEvent.VK_UNDERSCORE); break;
  ...

See https://coderanch.com/t/544719/java/Robot-symbols for the complete example.

** My cry for help is directed at an actual desktop application developer... cough Andrew Thompson cough

  • Related