我有一个程序试图在按键上移动一个小三角形。大多数代码都在工作,但Key按键根本不影响船只。你能看看我的代码并帮我找到解决方案吗?感谢所有帮助。
我有一个名为Ship
的课程,如下所示:
import java.awt.Polygon;
import java.awt.Color;
public class Ship extends GameObject{
//position of vector points arrays
private int[] xpoints = {-10,0,10};
private int[] ypoints = {-20,0,-20};
Polygon shape = new Polygon(xpoints,ypoints,xpoints.length);
public Ship()
{
setShape(shape);
setX(300.0);
setY(300.0);
setColour(new Color(255,0,0));
}
}
GameObject
看起来像这样(浓缩):
import java.awt.Shape;
import java.awt.Color;
import java.awt.Rectangle;
abstract class GameObject {
//variables
private Shape shape;
private boolean alive;
private Color colour;
//getter/setter methods
public void setShape(Shape shape){this.shape = shape;}
public void setX(double x){this.x = x;}
public void setY(double y){this.y = y;}
public void setColour(Color colour){this.colour = colour;}
public void incX(double i){this.x += i;}
public void incY(double i){this.y += i;}
public Shape getShape(){return shape;}
public double getX(){return x;}
public double getY(){return y;}
public Color getColor(){return colour;}
public Rectangle getBounds(){return shape.getBounds();}
public GameObject()
{
setAlive(false);
setSpeed(0);
setFaceAngle(0.0);
setMoveAngle(0.0);
setX(0.0);
setY(0.0);
setColour(null);
}
}
我的主要源代码:
import java.awt.*;
import java.applet.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
public class Shipmovementtest extends Applet implements KeyListener{
Graphics2D g2d;
Ship ship = new Ship();
Shape shape;
public void init()
{
shape = ship.getShape();
addKeyListener(this);
}
public void paint(Graphics g)
{
g2d = (Graphics2D)g;
AffineTransform identity = new AffineTransform();
int width = getSize().width;
int height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,width,height);
g2d.translate(ship.getX(),ship.getY());
g2d.setColor(Color.RED);
g2d.fill(shape);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e)
{
int ke = e.getKeyCode();
switch(ke)
{
case KeyEvent.VK_LEFT:
ship.incX(-5);
break;
case KeyEvent.VK_RIGHT:
ship.incX(5);
break;
case KeyEvent.VK_UP:
ship.incY(5);
break;
case KeyEvent.VK_DOWN:
ship.incY(-5);
break;
}
repaint();
}
public void keyReleased(KeyEvent e){}
}
答案 0 :(得分:1)
我以为你正在扩展JPanel;)
无论如何,以下答案https://stackoverflow.com/a/9505232/948652将对您有用。
public void init() {
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}