我对java小程序相当新,并且一直在努力制作一个乌龟和野兔竞赛计划。逻辑工作正常但每当我添加图形时它都不显示图像。编译代码时没有错误,但不会显示图像。我的代码如下,任何帮助将不胜感激。
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
public class Main extends Applet
{
Image tortise;
Image hare;
Graphics screen;
public void init()
{
tortise = getImage(getDocumentBase(), "tortise.gif");
hare = getImage(getDocumentBase(), "hare.gif");
}
public void main()
{
Random random = new Random();
int rabbitPos = 0;
int turtlePos = 0;
int randomInt;
boolean raceWon = false;
while(raceWon == false)
{
randomInt = random.nextInt(9);
if(randomInt < 5)
{
turtlePos += 3;
}
else if(randomInt < 7)
{
turtlePos += 1;
}
else if(turtlePos - 6 < 0)
{
turtlePos = 0;
}
else
{
turtlePos -= 6;
}
randomInt = random.nextInt(9);
if(randomInt < 2)
{
rabbitPos += 9;
}
else if(randomInt < 5)
{
rabbitPos += 1;
}
else if(randomInt < 6)
{
if(rabbitPos - 12 < 0)
{
rabbitPos = 0;
}
else
{
rabbitPos -= 12;
}
}
else if(randomInt < 8)
{
if(rabbitPos - 2 < 0)
{
rabbitPos = 0;
}
else
{
rabbitPos -= 2;
}
}
screen.drawImage(this.tortise, turtlePos, 30, this);
screen.drawImage(this.hare, rabbitPos, 150, this);
if(rabbitPos >= 50 && turtlePos >= 50)
{
System.out.println("Tie");
raceWon = true;
} else if(rabbitPos >= 50)
{
System.out.println("Rabbit Won");
raceWon = true;
}
else if(turtlePos >= 50)
{
System.out.println("Turtle Won");
raceWon = true;
}
}
}
}
答案 0 :(得分:0)
main
screen.drawImage
不是绘画的方式loop
是非常危险的,因为您可能阻止负责更新屏幕和/或违反大多数UI工具包的单线程性质的线程MediaTracker
之类的内容来确保图像在尝试绘制之前已完全加载首先看看......
我建议您使用类似JPanel
和JFrame
这样的工作,我会避免使用applet,因为它们带来了一系列问题和问题,这些问题将继续影响你的生活困难...