2

一个简单的问题,可能不是那么简单的解决方案。我的代码应该在黑色背景上显示一个可以在屏幕上移动的三角形。什么都没有显示,只是一个无法右键单击的白色区域。它在 appletviewer 或 HTML 文档中都不起作用,并且不显示语法错误。我的代码有什么问题?

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 Runnable,KeyListener{

    Graphics2D g2d;
    Ship ship1 = new Ship();
    BufferedImage backbuffer;
    AffineTransform identity = new AffineTransform();
    Shape ship1shape;
    Thread gameloop;
    public void start()
    {
        gameloop = new Thread(this);
        gameloop.start();
    }
    public void run()
    {
        Thread t = Thread.currentThread();
        while(gameloop==t)
        {
        try
        {
            Thread.sleep(20);
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        repaint();
        }
    }
    public void stop()
    {
        gameloop = null;
    }

    public void init()
    {
        ship1shape = ship1.getShape();
        backbuffer = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
        g2d = backbuffer.createGraphics();
        addKeyListener(this);
        setFocusable(true);
        requestFocusInWindow();

    }
    public void update(Graphics g)
    {
        g2d.setTransform(identity);
        g2d.setPaint(Color.BLACK);
        g2d.fillRect(0,0,getSize().width,getSize().height);
        drawShip();
        paint(g);
    }
    public void keyTyped(KeyEvent e){}
    public void keyPressed(KeyEvent e)
    {
        int ke = e.getKeyCode();
        switch(ke)
        {
        case KeyEvent.VK_LEFT:
            ship1.setFaceAngle(ship1.getFaceAngle()-5);
            break;
        case KeyEvent.VK_RIGHT:
            ship1.setFaceAngle(ship1.getFaceAngle()+5);
            break;
        case KeyEvent.VK_UP:
            ship1.incX(-ship1.calcAngleMoveX(ship1.getFaceAngle())*ship1.velocity);
            ship1.incY(-ship1.calcAngleMoveY(ship1.getFaceAngle())*ship1.velocity);
            break;
        case KeyEvent.VK_DOWN:
            ship1.incX(ship1.calcAngleMoveX(ship1.getFaceAngle())*ship1.velocity);
            ship1.incY(ship1.calcAngleMoveY(ship1.getFaceAngle())*ship1.velocity);
            break;
       }
    }
    public void paint(Graphics g)
    {
        g2d.drawImage(backbuffer,0,0,this);
    }
    public void keyReleased(KeyEvent e){}
    public void drawShip()
    {
        g2d.setTransform(identity);
        g2d.translate(ship1.getX(),ship1.getY());
        g2d.rotate(Math.toRadians(ship1.getFaceAngle()));
        g2d.setColor(ship1.getColor());
        g2d.fill(ship1.getShape());
    }
}
4

1 回答 1

5

最终paint你需要将缓冲区实际绘制到真正的图形g上。目前您只在缓冲区中绘画。

所以正确的代码是

public void paint(Graphics g)
{
    g.drawImage(backbuffer,0,0,this);
}
于 2013-06-14T18:40:53.647 回答