Reputation: 21
This is a break the brick type of game where the user cannot let the ball fall below the paddle. By the way paddle_x is sets the x coordinate of the paddle. I have a MouseListener that works very well however, the KeyListener does not. I am wondering what I am doing wrong and if anyone has any suggestions.
public PaintSurface() {
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
if (e.getX() - 30 - paddle_x > 5)
english = 1.5f;
else if(e.getX() - 30 - paddle_x < -5)
english = - 1.5f;
else
english = 1.0f;
paddle_x = e.getX() - 30;
}
});
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getID() == KeyEvent.KEY_TYPED){
if(e.getKeyChar() == KeyEvent.VK_RIGHT){
paddle_x += 30;
}
else if (e.getKeyChar() == KeyEvent.VK_LEFT){
paddle_x -= 30;
}
}
}
});
ball = new Ball(20);
}
Upvotes: 0
Views: 86
Reputation: 8348
The Component which has a registered KeyListener
must have focus
for the KeyListener
to fire. Call requestFocus
on the Component to request that the component has focus, or use KeyBindings (recommended)
In addition, the keyPressed
method has a conditional that checks the ID against KeyEvent.KEY_TYPED
events (which will never happen).
Upvotes: 3