我正在尝试将 Java KeyListener 合并到我的移动对象中,左/右箭头影响 x 轴 (xSpeed) 坐标,上/下箭头影响 y 轴 (ySpeed)。由于某种原因,我只是无法连接对象和 KeyListener。请帮帮我?谢谢!
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class Action
{
private static final int GRAVITY = 1;
private int ballDegradation = 8;
private Ellipse2D.Double circle;
private Color color;
private int diameter;
private int xPosition;
private int yPosition;
private final int groundPosition;
private final int topPosition;
private final int leftSidePosition;
private final int rightSidePosition;
private Canvas canvas;
private int ySpeed = -1;
private int xSpeed = 8;
public Action(int xPos, int yPos, int ballDiameter, Color ballColor,
int groundPos, int topPos, int leftSidePos, int rightSidePos, Canvas drawingCanvas)
{
xPosition = xPos;
yPosition = yPos;
color = ballColor;
diameter = ballDiameter;
groundPosition = groundPos;
topPosition = topPos;
leftSidePosition = leftSidePos;
rightSidePosition = rightSidePos;
canvas = drawingCanvas;
}
public void draw()
{
canvas.setForegroundColor(color);
canvas.fillCircle(xPosition, yPosition, diameter);
}
public void erase()
{
canvas.eraseCircle(xPosition, yPosition, diameter);
}
public void move()
{
erase();
ySpeed += GRAVITY;
yPosition += ySpeed;
xPosition += xSpeed;
if(yPosition >= (groundPosition - diameter) && ySpeed > 0)
{
yPosition = (int)(groundPosition - diameter);
ySpeed = -ySpeed + ballDegradation;
}
if(yPosition <= topPosition && ySpeed < 0)
{
yPosition = (int)topPosition;
ySpeed = -ySpeed + ballDegradation;
}
if(xPosition <= leftSidePosition && xSpeed <0)
{
xPosition = (int)leftSidePosition;
xSpeed = -xSpeed + ballDegradation;
}
if(xPosition >= (rightSidePosition - diameter) && xSpeed > 0)
{
xPosition = (int)(rightSidePosition - diameter);
xSpeed = -xSpeed + ballDegradation;
}
draw();
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
ySpeed = -ySpeed --;
break;
case KeyEvent.VK_DOWN:
ySpeed = -ySpeed ++;
break;
case KeyEvent.VK_LEFT:
xSpeed = xSpeed --;
break;
case KeyEvent.VK_RIGHT :
xSpeed = xSpeed ++;
break;
}
}
}