[java] How to use KeyListener

I am currently trying to implement a keylistener in my program so that it does an action when I pressed an arrow key, the object in my program either moves left or right.

Here is the moving method in my program

public void moveDirection(KeyEvent e)
    {
        int move = 0;
        int r = K.getRow();
        int c = K.getCol();
        if (e.getKeyCode() == 39) move = 1; //KeyEvent.VK_RIGHT
        if (e.getKeyCode() == 37) move = 2; //KeyEvent.VK_LEFT
        //if (e.getKeyCode() == KeyEvent.VK_DOWN) move = 3;

        switch (move)
        {
            case 1: if (inBound(r, c+1))
                        K.setLocation(r ,c+1); 
                    if (inBound(r, c-1) && frame2[r][c-1] == K)
                        frame2[K.getRow()][K.getCol()-1] = null; 
                    break; //move right 39
            case 2: K.setLocation(K.getRow(), K.getCol()-1); break; //move left 37
            //case 3: b.setLocation(b.getRow()+1, b.getCol()); break; //move down
            default: return;
        }        
        processBlockList();
    }

I am wondering how the program is supposed to read in (KeyEvent) e. I cannot really type in an arrowkey....

Please help!

edit: I also need to know what I need to add to my code so that my program waits about 700 milliseconds for a keyinput before moving on to another method

This question is related to java awt keylistener

The answer is


Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings


In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.


The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

  1. Make one Key listener class as

    class MyListener implements KeyListener{
    
       // override all the methods of KeyListener interface.
    }
    
  2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

  3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

    JFrame f=new JFrame();
    f.addKeyListener(new MyKeyListener);