Sign in to follow this  
joe96

Problem with Java KeyListener

Recommended Posts

joe96    102

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.

Share this post


Link to post
Share on other sites
Nicholas Kong    1535

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.

Edited by warnexus

Share this post


Link to post
Share on other sites
CryoGenesis    528

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.

Edited by CryoGenesis

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this