import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends Applet implements Runnable
{
//2bufery
Image dbImage;
Graphics dbGraphics;
boolean going = true;
int x, y, xspeed, yspeed, radius;
Thread th = new Thread();
public void init()
{
x = getSize().width/2;
y = getSize().height/2;
xspeed = 2;
yspeed = 2;
radius = 8;
}
public void start()
{
th.start();
}
public void stop()
{
going = false;
}
public void destroy()
{
going = false;
}
public void run()
{
while(going)
{
x += xspeed;
y += yspeed;
repaint();
try
{
Thread.sleep(500);
}
catch(InterruptedException ie)
{
}
}
}
public void update(Graphics g)
{
if(dbImage == null)
{
dbImage = createImage(this.getSize().width, getSize().height);
dbGraphics = dbImage.getGraphics();
}
dbGraphics.setColor(this.getBackground());
dbGraphics.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbGraphics.setColor(this.getForeground());
paint(dbGraphics);
g.drawImage(dbImage,0,0,this);
}
public void paint (Graphics g)
{
g.setColor(Color.pink);
g.fillOval(x-radius, y-radius, radius*2, radius*2);
}
}
移动球时遇到问题。 我已经完成了本教程:
当我运行程序时,它会执行除run
方法之外的所有方法(我通过将System.out.println
放在某些代码部分中找到了这一点),但我无法弄清楚原因。有人可以帮我吗?
答案 0 :(得分:6)
您需要将Runnable
的实例传递给Thread
构造函数:
Thread th = new Thread();
应该是:
Thread th = new Thread(this);