Java.awt.Robot inside games?
I am trying to simulate a key press using the code below. When I open notepad it works great, but when I open the game I want to use it in it does nothing. So keystrokes don't work. I tried to simulate mouse movement and clicks, these actions actually work. Does anyone know how to fix this problem?
I found this question, How can I use java.awt.Robot inside games? but I can't add a comment or anything.
package MyProject;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class KeyStroke {
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
robot.delay(3000);
robot.keyPress(KeyEvent.VK_Q);
robot.keyPress(KeyEvent.VK_W);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_T);
robot.keyPress(KeyEvent.VK_Y);
}
}
source to share
You probably want to press and release keys to simulate a key press, i.e. your current code will hold Q, W, E, R, T, and Y until the release starts. Alternatively, you can hold them for a small amount of time, because that caused some problems for me when I did something like this.
Code
package MyProject;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class KeyStroke {
private static Robot robot;
public static void main(String[] args) throws AWTException {
robot = new Robot();
robot.delay(3000);
keystroke(KeyEvent.VK_Q);
keystroke(KeyEvent.VK_W);
keystroke(KeyEvent.VK_E);
keystroke(KeyEvent.VK_R);
keystroke(KeyEvent.VK_T);
keystroke(KeyEvent.VK_Y);
}
private static void keystroke(int key) {
robot.keyPress(key);
robot.delay(100); // hold for a tenth of a second, adjustable
robot.keyRelease(key);
}
}
source to share
As opposed to above - where you add your key listener
public class BetaTest {
public static void main (String[] args){
new BetaTest().startUp();
}
private void startUp() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
final KeyAdapter ka = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println("key pressed");
}
};
frame.addKeyListener(ka);
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
KeyEvent ke = new KeyEvent(frame, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_A, 'a');
ka.keyPressed(ke);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(r);
t.setDaemon(true);
t.start();
}
}
and the output is suprise
key pressed
source to share