gpt4 book ai didi

Java KeyListener 与移动对象

转载 作者:行者123 更新时间:2023-11-30 04:46:53 24 4
gpt4 key购买 nike

我正在尝试将 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;
}
}
}

最佳答案

  • 不要使用 API、方法或 e.i. 的保留 Java 名称,Action 可以是 MyAction

  • 不要使用 AWT Canvas(仅当您有非常重要的原因时,OpenXxx、CAD、CAM...),而使用 JPanel 或 JComponent

  • (没有人知道您的其余代码)不要将 AWT 组件与 Swing JComponent 混合使用

  • 如果您将使用 JPanel 或 JComponent,则使用 KeyBindings而不是 KeyListener

  • 否则,您必须为 Canvas 设置Focusable,并且在对 Focus 进行任何更改后,您必须将 Focus 设置回 Canvas,这是 KeyListener 的问题

关于Java KeyListener 与移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com