I would like to be able to have background input in Java. I set up the keyboard listener the usual way (I think). This code works fine, but whenever the program loses focus, the keys stop updating. The update method is ran 60 times a second and continues to be ran while the frame is out of focus, but the keys don't update (If a key is pressed when the frame loses focus, the program will act as if you are holding it down).
My question: is there a way to allow Java to receive background inputs when the frame is out of focus? I would prefer a solution without external libraries but any will help.
The reason I would like to do this is because my program will have multiple frames and I need to be able to receive input in the main frame even if it is not in focus, including when none of the frames are in focus.
Not sure how helpful it will be but my current code for listening for key events is below.
Here I add the key listener to my main class.
public static Keyboard key;
key = new Keyboard();
addKeyListener(key);
This code is from my Keyboard class
private boolean[] keys = new boolean[120];
public boolean up, down, left, right;
public void update() {
up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}