Search code examples
javakeypressawtrobot

A loop that would type a random character using robot.keyPress


I'm trying to write a random character using robot.keyPress.

So far I've opened the notepad, wrote in it and saved it. If I run this program in a loop it would always save the notepad with the same name and therefore replacing the previous one.

I want to save multiple notepads(with different names) possibly by typing a random letter before saving it.


Solution

  • To have Robot perform a random keypress in a quick and dirty fashion, you'll want to first make a list of acceptable KeyEvent constants (a-zA-Z0-9, etc.) Assuming you put that list together:

    int[] keys = new int[]{KeyEvent.VK_A, KeyEvent.VK_B, ... }; // Your list of KeyEvent character constants here, adapt as desired. 
    
    // Start optional for loop here if you want more than 1 random character
    int randomValue = ThreadLocalRandom.current().nextInt(0, keys.length);
    
    Robot.keyPress(keys[randomValue]);
    

    Tweak to your needs.