0

我有一个程序试图在按键上移动一个小三角形。大部分代码都在工作,但按键根本不会影响飞船。你能看看我的代码并帮助我找到解决方案吗?感谢所有帮助。

我有一个名为的类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){}
}
4

1 回答 1

1

我以为你在扩展 JPanel ;)

无论如何,以下答案https://stackoverflow.com/a/9505232/948652将为您工作。

public void init() {
    addKeyListener(this);
    setFocusable(true);
    requestFocusInWindow();
}
于 2013-06-06T17:43:41.960 回答