5

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DSdavidDS
  • 153
  • 1
  • 2
  • 12

4 Answers4

12

http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Check this tutorial

If it's a UI based application , then " 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" you can use GlassPane or Timer class to fulfill the requirement.

For key Event:

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = -1;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -1;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 1;
    }
}

check this game example http://zetcode.com/tutorials/javagamestutorial/movingsprites/

Nayuki
  • 17,911
  • 6
  • 53
  • 80
Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128
10

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

COD3BOY
  • 11,964
  • 1
  • 38
  • 56
2

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);
    
René Vogt
  • 43,056
  • 14
  • 77
  • 99
Gyan
  • 37
  • 4
2

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.

Astrolamb
  • 171
  • 12
  • Thank you. This is exactly what I needed. Is the reason that others' answers don't call for focus and don't seem to need it (but I do need it) is that I am using BOTH the MouseListener and the KeyListener? – Para Parasolian Mar 31 '22 at 13:58
  • 1
    @ParaParasolian that's possible, but I don't think that's likely. It's more likely that the others are adding their listeners to a JFrame instead of a JComponent. JComponents don't default to being focusable since they are often used as containers rather than direct UI elements, so they usually don't need to be focusable. – Astrolamb Apr 01 '22 at 12:19
  • I think I understand. You are right -- I am using it with a JPanel, not a JFrame. – Para Parasolian Apr 03 '22 at 13:02