Implementing Runnable
Here's the code for this applet:
TH2.java:
//Thread Example Two:
// Implementing Runnable
import java.awt.*;
import java.applet.*;
public class TH2 extends Applet implements Runnable{
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 Thread(this); //initiate the thread
bt.start(); //start the thread running
}
public void run(){
boolean move_rt = true;
while(true){
if(move_rt && x>390){
move_rt = false;
}
if(!move_rt && x<5){
move_rt = true;
}
if(move_rt) mvX(3);
else mvX(-3);
try{
Thread.sleep(100);
}catch(InterruptedException e){};
}
}
public void mvX(int i){
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);
}
}