Problem with Java KeyListener

Started by
1 comment, last by CryoGenesis 10 years, 11 months ago

I'm working on a 2d game in java. I have a problem using the key listener to move the character. I might be typing the code wrong or something but i need help fixing it. This is my player.java class:

import java.awt.event.*;

public class Player implements KeyListener{
public int x = 500, y = 300;
public int health = 100;
public int dx;
public int dy;
public Player(){
x = x + dx;
y = y + dy;
}
public int getXPos(){
return x;
}
public int getYPos(){
return y;
}
public int getHealth(){
return health;
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_W){
dy = 2;
}
if(keyCode == KeyEvent.VK_A){
dx = -2;
}
if(keyCode == KeyEvent.VK_S){
dy = -2;
}
if(keyCode == KeyEvent.VK_D){
dx = 2;
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_W){
dy = 0;
}
if(keyCode == KeyEvent.VK_A){
dx = 0;
}
if(keyCode == KeyEvent.VK_S){
dy = 0;
}
if(keyCode == KeyEvent.VK_D){
dx = 0;
}
}
}
In a different class i draw the character as a rectangle like this:
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(p.getXPos(), p.getYPos(), 25, 25);
}
The problem is the character doesn't move when i press the buttons. I'm relatively new to java. Any help will be greatly appreciated.
Advertisement

put this code in your constructor: addKeyListener(this)

Rule of thumb: always addKeyListener to a class that implements the KeyListener interface.

Even though you override the methods of the KeyListener interface, if you do not addKeyListener to your class, then it does not have listeners to help the class response to events generated by the user.

Addition to that ^

Make sure you add it to the different class's constructor (JPanel I'm guessing), not the player constructor.

Also, adding "setFocusable(true)" might fix it if it still doesn't work.

This topic is closed to new replies.

Advertisement