I am doing a fighting game in Java for a project and trying to get an image in order to move and repaint on a keyboard responsive panel (keyEvents). I am trying to accomplish this by switching the keyPressed method by adding keyListener to the panel. I gave an example in my Java book and code that I wrote in much the same way, but it just won't work.
What I'm really interested in is that it doesn't react at all to keyEvents. The program compiles everything and everything, but nothing happens. I have no idea what is going wrong. It does not reach the breakpoint in the method keyPressed()if I do this, and will not do println()it if I posted it. Thus, the method keyPressed()does not respond at all. I also tested and made sure that the panel is focusable, so I am sure that it has keyboard focus.
public class MovePanel extends JPanel implements KeyListener {
private ImageIcon currentImage, facingLeft, facingRight;
private int position;
private final int MOVEMENT;
private GameFrame gameFrame;
private URL lefturl, righturl;
public MovePanel(GameFrame gameFrame) {
this.gameFrame = gameFrame;
addKeyListener(this);
lefturl = getClass().getResource("/Images/facingLeft.jpg");
righturl = getClass().getResource("/Images/facingRight.jpg");
facingLeft = new ImageIcon(lefturl);
facingRight = new ImageIcon(righturl);
currentImage = facingLeft;
position = 50;
MOVEMENT = 30;
setBackground(Color.red);
setPreferredSize(new Dimension(600,300));
setFocusable(true);
}
public void paintComponent(Graphics page) {
super.paintComponent(page);
currentImage.paintIcon(this, page, position, 170);
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
currentImage = facingRight;
position -= MOVEMENT;
break;
case KeyEvent.VK_RIGHT:
currentImage = facingRight;
position += MOVEMENT;
break;
case KeyEvent.VK_ESCAPE:
gameFrame.setMenuPanelActive();
break;
}
repaint();
}
}
Does anyone know why this is not working? Why keyPressed()won't the method respond?
source
share