簡體   English   中英

應該移動球的程序,但不執行方法運行

[英]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);
    }

}

移動我的球有問題。 我已經完成了本教程:

當我運行程序時,它執行除run方法之外的所有方法(我通過將System.out.println放在某些代碼部分中找到了),但我無法弄清楚原因。 有人可以幫我嗎?

您需要將Runnable的實例傳遞給Thread構造函數:

Thread th = new Thread();

應該:

Thread th = new Thread(this);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM