我想使用左右箭头键在黑色背景上移动白色圆圈。 KeyListener正在运行(使用System.out.print),但是当按下键时圆圈不会移动。我认为这与x和y位置(xPos,yPos)有关。
private static final int SPEED = 50, BALL_SIZE = 50;
private int dx;
private int xPos, yPos;
public Background() {
addKeyListener(this);
setBackground(Color.BLACK);
// the starting point of ball
xPos = 100;
yPos = 700;
dx = SPEED;
}
@Override
public void actionPerformed(ActionEvent e) {
// screen size
int width = getWidth();
xPos += dx;
// boundaries
if (xPos < 100) {
xPos = 100;
dx = SPEED;
}
else if (xPos > width - BALL_SIZE) {
xPos = width - BALL_SIZE;
dx = -SPEED;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) { // right arrow key
dx++;
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) { // left arrow key
dx--;
}
else if (e.getKeyCode() == KeyEvent.VK_SPACE) { // space bar
// shoot laser!
}
System.out.println("After");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillOval(xPos, yPos, BALL_SIZE, BALL_SIZE);
}