A simple question with a perhaps not so simple solution. My code is supposed to show a triangle on a black background that can be moved around onscreen. Only nothing displays, just a white area that can't be right-clicked on. It does not work in either the appletviewer or an HTML document, and shows no syntax errors. What is wrong with my code?
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());
}
}
In the end of paint
you need to actually draw the buffer to the real graphics g
. Currently you are only painting in the buffer.
So correct code would be
public void paint(Graphics g)
{
g.drawImage(backbuffer,0,0,this);
}