-1

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.

Austin Schaefer
  • 695
  • 5
  • 19
Libraa
  • 17
  • 4
  • The context of your question is a bit unclear; are you working with physical robots and looking to make one press a key at random on a physical keyboard? Or are you simply trying to add a random character to a file through software alone? – Austin Schaefer Jun 18 '19 at 10:17
  • 1
    I'm sorry. I'm just testing the robot. command alone. I'm trying to add a random character to a file. – Libraa Jun 18 '19 at 10:18
  • To the file's content or to it's name? – Austin Schaefer Jun 18 '19 at 10:19
  • I just need to save the file with same content multiple times. I can achive that by saving it by a different name. However in order to save it with a different name I would have to make a loop to type a diffrent character everytime it passes. – Libraa Jun 18 '19 at 10:22
  • I added a potential answer below. – Austin Schaefer Jun 18 '19 at 10:36

2 Answers2

0

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.

Austin Schaefer
  • 695
  • 5
  • 19
0

This question is not so much asbout java.awt.robot but more about random value generation. A simplke solution could be this.

Random rnd = new Random();
int key = KeyEvent.VK_UNDEFINED;
while (key < KeyEvent.VK_A || key > KeyEvent.VK_Z) {
    key = rnd.nextInt();
}
robot.keyPress(key);

To avoid useless looping use this:

Random rnd = new Random();
final int range = (KeyEvent.VK_Z + 1) - KeyEvent.VK_A;
int key = Math.abs(rnd.nextInt()) % range;
robot.keyPress(key);
Würgspaß
  • 4,660
  • 2
  • 25
  • 41