Jump to content

  • Log In with Google      Sign In   
  • Create Account

We need your feedback on a survey! Each completed response supports our community and gives you a chance to win a $25 Amazon gift card!


Problem with Java KeyListener


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 joe96   Members   -  Reputation: 102

Like
0Likes
Like

Posted 20 April 2013 - 11:49 AM

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.


Sponsor:

#2 warnexus   Prime Members   -  Reputation: 1505

Like
0Likes
Like

Posted 20 April 2013 - 08:08 PM

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, 20 April 2013 - 09:44 PM.


#3 CryoGenesis   Members   -  Reputation: 499

Like
0Likes
Like

Posted 24 April 2013 - 02:32 PM

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, 24 April 2013 - 02:33 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS