Extending the Thread Class

Here's the code for this applet:

TH1.java:

//Thread Example One: // Extending Thread Class import java.awt.*; import java.applet.*; public class TH1 extends Applet{ Thread bt; //declare the thread Image offI; Dimension d; int x=10; public void init(){ d = getSize(); offI = createImage(d.width, d.height); bt = new BALL_THREAD(this); //initiate the thread bt.start(); //start the thread running } public void mvX(int i){ // this method is called by the Thread class x+=i; repaint(); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Graphics offG = offI.getGraphics(); offG.setColor(Color.yellow); offG.fillRect(0,0,d.width,d.height); offG.setColor(Color.blue); offG.fillOval(x,40,40,40); g.drawImage(offI,0,0,this); } }

BALL_THREAD.java:

public class BALL_THREAD extends Thread{ TH1 app; int x; BALL_THREAD(TH1 th1){ app = th1; } public void run(){ boolean move_rt = true; while(true){ if(move_rt && app.x>390){ move_rt = false; } if(!move_rt && app.x<5){ move_rt = true; } if(move_rt) app.mvX(3); else app.mvX(-3); try{ Thread.sleep(100); }catch(InterruptedException e){}; } } }