user3520416
user3520416

Reputation: 1

Java: My key isn't being adapted by KeyListener

I'm trying to get my minigame, (paint) to detect keyboard clicks, I.e, Up arrow key to continue the line of an oval. The problem is that when I run the program and enter the up arrow key, or down or left or right, the program doesn't do anything. Please help.

Here's all the code:

package MiniGame;

import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;

public class GameTest extends JFrame{
    int x;
    int y;


    //This class detects the keys pressed.
    public class Actionlistener extends KeyAdapter{
        public void KeyPressed(KeyEvent ke){
            int Listen = ke.getKeyCode();

            if(Listen == ke.VK_UP )  {y--;}
            if(Listen == ke.VK_LEFT) {x--;}
            if(Listen == ke.VK_DOWN) {y++;}
            if(Listen == ke.VK_RIGHT){x++;}
        }

        public void KeyReleased() {
            //There's no code here yet.
        }
    }


    //The constructor that initialises some components.
    public GameTest() {
        addKeyListener(new Actionlistener());
        setTitle("Game Test");
        setSize(750, 750);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);

        x = 150;
        y = 150;
    } //Paint method.

    public void paint(Graphics g) {
        g.fillOval(x, y, 20, 20);
        repaint();
    }

    //Creating an object
    public static void main(String[] args){
        new GameTest();
    }
}

Upvotes: 0

Views: 59

Answers (1)

camickr
camickr

Reputation: 324147

Don't use a KeyListener! Swing was designed to be used with Key Bindings.

See Motion Using the Keyboard for more information why you should NOT use a KeyListener and working examples of Key Bindings to get you started.

Upvotes: 1

Related Questions