I'm trying to make a Pong game for my class, but my KeyListener won't fire to its respective methods. I've looked on various questions, but its solutions haven't done any good for me.
I have a class that extends JPanel
, and in its constructor, I have the following methods:
public final class GamePanel
extends javax.swing.JPanel
implements ActionListener, KeyListener {
public GamePanel(MainWindow Parent, WelcomePanel Sister) {
parent = Parent;
sister = Sister;
ball = new Ball(this);
Player1 = new Paddle(this, "left", "user");
Player2 = new Paddle(this, "right", "user");
setVisible(true);
Timer t = new Timer(60, this);
t.start();
addKeyListener(this);
this.requestFocusInWindow();
setFocusable(true);
}
public void keyPressed(KeyEvent event) {
Player1.keyPressedEvent(event) // Get's KeyCode, puts it in a switch and moves
// the increment of the paddle accordingly.
Player1.keyPressedEvent(KeyEvent event)
:
public void keyPressedAction(KeyEvent event) {
int code = event.getKeyCode();
if (this.side.equals("left")) {
switch (code) {
case KeyEvent.VK_UP:
this.yIncrement = 10;
break;
case KeyEvent.VK_DOWN:
this.yIncrement = -10;
break;
case KeyEvent.VK_LEFT:
this.xIncrement = -10;
break;
case KeyEvent.VK_RIGHT:
this.xIncrement = 10;
break;
}
}
else if (this.side.equals("right")) {
switch (code) {
case KeyEvent.VK_W:
this.yIncrement = 10;
break;
case KeyEvent.VK_S:
this.yIncrement = -10;
break;
case KeyEvent.VK_A:
this.xIncrement = -10;
break;
case KeyEvent.VK_D:
this.xIncrement = 10;
break;
}
}
}
Could the reason for the malfunctioning be some interference with the ActionListener
? I'm quite new to Java, but having looked at the code of some of my friend's, there using this and having no problems. The issue is that the paddle's don't move at all.