user3398900
user3398900

Reputation: 845

how can i detect which key in keyboard is typed in java

Hi all here i am trying to detect the button clicked and based upon that i want to determine some actions Scenario is i must be able to do some action if a user clicks on up arrow or "A" button in the keyboard.. it is throwing an error as off now and is quite obvious

enter code here
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub
    switch (e.getKeyCode()) {
    case KeyEvent.VK_UP || e.getKeyChar("a"):


        break;

    default:
        break;
    }

}

How can i achieve it ? Thanks in advance

Upvotes: 1

Views: 223

Answers (2)

Yoctoboy
Yoctoboy

Reputation: 540

My mate and I did a project in which we needed this, and the code we used looks like :

public final synchronized void keyPressed(KeyEvent e){
    int key = e.getKeyCode();
    //stuff
}

This method is called automatically as soon as a key gets pressed.

Upvotes: 1

camickr
camickr

Reputation: 324207

Don't use a KeyListner.

Swing was designed to be used with Key Bindings.

So you create an Action for each KeyStroke you want to handle and then you bind the KeyStroke to the Action. The above tutorial will explain in more detail and there are plenty of example on the forum.

You can also check out Motion Using the Keyboard which compares KeyEvent and KeyBinds with working examples of both.

Upvotes: 1

Related Questions