Search code examples
javaswingkey-bindings

Java: How to keep my application functioning properly even If I'm having a game open while it's running at the background


I know the title didnt say much, but here I go with a clearer explanation:

I have made a tool/app in netbeans that extends JFrame. It has a button and i've added a keyListener when the button is pressed. It gets if the VK_DOWN button is pressed, if yes, it presses it 4 times and then presses enter. this works very fine, but I want to use this in a game. But when I have the app running, if i click on something else, it takes away the priority (i hope thats the right word here..), it doesnt work anymore unless I click on the app and make it top priority again..

Here is the code for the button:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    jButton1.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {

    }
    public void keyTyped(KeyEvent e) {
    // TODO: Do something for the keyTyped event
    }
    public void keyPressed(KeyEvent e) {
    // TODO: Do something for the keyPressed event
        if (e.getKeyCode() == e.VK_L){
            System.out.println("Works");
        }
        if (e.getKeyCode() == e.VK_DOWN){
            System.out.println("Down Arrow Pressed!");
            e.setKeyCode(e.VK_DOWN);
            e.setKeyCode(e.VK_DOWN);
            e.setKeyCode(e.VK_DOWN);
            e.setKeyCode(e.VK_DOWN);
            e.setKeyCode(e.VK_ENTER);

        }
    }
    });
}

I want to press the VK_DOWN arrow key in the game and let the app press it 4 times and then press enter by itself. This works only when I'm running the app on top of everything else; but if Im running the game, the game takes the higher priority and so the app dont work ..

Please help.


Solution

  • You cannot do what you are looking to do with Java unless you use some native code.