在所有这些方法中,正在运行什么以及以什么顺序运行?我想第一个要问的问题是先运行什么?
为什么 th.start() 会启动 run()?
import java.applet.*;
import java.awt.*;
import javax.swing.JFrame;
public class BallApplet extends Applet implements Runnable {
int x_pos = 10;
int y_pos = 100;
int radius = 20;
private Image dbImage;
private Graphics dbG;
public void init() {
// setBackground(Color.BLUE);
}
public void start() {
Thread th = new Thread (this);
th.start();
}
public void stop() {}
public void destroy() {}
public void run() {
// 20 second delay per frame refresh (animation doesn't
// need to be perfectly continuous)
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true) {
x_pos++;
repaint();
try {
Thread.sleep(20);
}
catch (InterruptedException ex) {
System.out.println("Caught!");
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public void update(Graphics g) {
// implements double buffering
// drawing on doublebufferImage, note the dbG=dbImage.getGraphics(), so everything dbG.whatever() is
// drawing on the Image's graphics which is later drawn with g.drawImage()
// initialize buffer
if (dbImage == null) {
dbImage = createImage (this.getSize().width, this.getSize().height);
dbG = dbImage.getGraphics();
}
// clear screen in background
dbG.setColor(getBackground()); // gets background color
dbG.fillRect(0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbG.setColor(getForeground());
paint(dbG);
// draw image on the screen
g.drawImage(dbImage, 0, 0, this);
}
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x_pos-radius, y_pos-radius, 2*radius, 2*radius);
}
}