Of all these methods what’s being run and in what order?? I guess the first question to ask is whats being run first?
And why does th.start() 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); } }
The
init()andstart()methods are invoked first.That in turn creates a
Threadand starts that thread, which causes this class’srun()method to be invoked.The
paint()method is invoked by Swing independently in the GUI event handling thread, if Swing detects that the applet needs to be redrawn.I note that the class’s main
run()method also repeatedly callsrepaint(). That explicitly tells the GUI thread to invokeupdate().