简体   繁体   中英

Program that should move a ball, but method run is not executed

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);
    }

}

I have a problem with moving my ball. I have done it with this tutorial:

While I'm running the program, it executes all methods except the run method (I found that out by putting System.out.println in some code sections), but I can't figure out why. Can someone help me out?

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

Thread th = new Thread();

should be:

Thread th = new Thread(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM