loserlobster
loserlobster

Reputation: 23

In java how do I check if a user is pressing a certain key?

I am trying to make a hotkey program that runs in the background, and I can not figure out how to make it check when a certain key is pressed (In this case the minus key). I need the program to wait for a key to be pressed and then the program checks if that key is the minus key.

An example of my program as is now in pseudo code is somewhere along these lines.

while(true)
    {
        int pressedKey = userInputedKey;
        if(pressedKey == KeyEvent.VK_MINUS)
        {
            //action to be executed
        }
    }

I have found a lot of suggestions on other threads to use KeyListener but I might not be using it properly, so if your response is to use KeyListener please explain how to use it thoroughly (to be Exact I don't understand how when a KeyEvent is instantiated it already has the input of whatever key was pressed as the keyCode in that KeyEvent, so if I use it in the call to the KeyListener I will not get the proper results). Granted I do not know much about KeyEvent or KeyListener, so I might have not been attempting at the right way around my problem by using a KeyListener.

Upvotes: 2

Views: 6657

Answers (2)

Javasick
Javasick

Reputation: 3003

If you want to use global hotkeys, when program catch keypress event in any application - try use JKeyMaster library (supports global hotkweys in Windows, Linux and MAC OS)

Upvotes: 1

Bahramdun Adil
Bahramdun Adil

Reputation: 6089

You can use the KeyEvent to get the key code, and then check it.

E.g:

someCompunent.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_MINUS) {
           // do the stuff
        }
    }
});

Upvotes: 1

Related Questions