gpt4 book ai didi

java - 应该 move 球的程序,但不执行方法运行

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:36 29 4
gpt4 key购买 nike

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

}

我的球 move 有问题。我已经完成了本教程:

当我运行程序时,它会执行除 run 方法之外的所有方法(我通过将 System.out.println 放在某些代码部分中发现了这一点) ,但我不明白为什么。有人可以帮我吗?

最佳答案

您需要将 Runnable 的实例传递给 Thread 构造函数:

Thread th = new Thread();

应该是:

Thread th = new Thread(this);

关于java - 应该 move 球的程序,但不执行方法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003862/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com