I’m trying to incorporate Java KeyListener to my moving object with the left/right arrows affecting the x-axis (xSpeed) coordinates and the up/down arrows affecting the y-axis (ySpeed). I’m just not able to connect the object and the KeyListener for some reason. Help me please? Thanks!
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;
}
}
}
don’t use reserved Java names for API, Method or e.i.,
Actioncould beMyActiondon’t use AWT Canvas (onyl if you have got really important reason, OpenXxx, CAD, CAM…), use JPanel or JComponent instead
(nobody knows rest of your code) don’t mixing AWT Component with Swing JComponent
in the case that you’ll use JPanel or JComponent, then use KeyBindings rather than KeyListener
otherwise you have to setFocusable for Canvas and after any changes about Focus you have to set Focus to the Canvas back, this is issues with KeyListener