I am making a Pong game and I am having trouble making the paddles move. I have already drawn them onto my content pane and I want to use a key listener to make them move. I have heard about using key binding, but I do not understand the tutorial of how to do it. My teacher has not taught any of this material yet, and he does not plan on it. So any help would be greatly appreciated. I have a key listener setup but does not move the object at all. Thanks again! :)
} else if (buttonText.equals("Vs. Comp")) {
name1 = JOptionPane.showInputDialog(null, "Name of Player One:", "Player One", JOptionPane.OK_CANCEL_OPTION);
contentPane.remove(pane);
contentPane.validate();
contentPane.remove(singleplayer);
contentPane.validate();
contentPane.remove(multiplayer);
contentPane.validate();
contentPane.remove(comp);
contentPane.validate();
p = new PlayerOne();
p.paintPaddle();
contentPane.validate();
}
}
}
private class PlayerOne extends Component implements KeyListener {
int x, y = 180;
public int width = contentPane.getWidth();
public void run() {
paintPaddle();
doNothing(PAUSE);
setFocusable(true);
addKeyListener(this);
}
public void paintPaddle() {
Graphics g = contentPane.getGraphics();
g.setColor(Color.RED);
g.fillRect(1, y, 5, (width / 12));
repaint();
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
y = getY();
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y += 10;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
y -= 10;
repaint();
}
repaint();
}
public void keyReleased(KeyEvent e) {
repaint();
}
}