3
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),但我不知道为什么。有人可以帮我吗?

4

1 回答 1

6

You need to pass an instance of Runnable to Thread constructor:

Thread th = new Thread();

should be:

Thread th = new Thread(this);
于 2013-08-01T20:28:39.633 回答