/**The following applet shows 8 pictures randomly. We use the
class Thread.
*/
import java.awt.*;//package of Graphics
import java.applet.Applet;
public class AnimThread extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
// See comments below
Thread ThisThread;
Image Buffer;
Graphics g;
Image pic0, pic1, pic2, pic3, pic4, pic5, pic6, pic7;
public void init()//Initialize pictures
{
pic0 = getImage(getCodeBase(),"Images/Malt0.jpg");
pic1 = getImage(getCodeBase(),"Images/Malt1.jpg");
pic2 = getImage(getCodeBase(),"Images/Malt2.jpg");
pic3 = getImage(getCodeBase(),"Images/Malt3.jpg");
pic4 = getImage(getCodeBase(),"Images/Malt4.jpg");
pic5 = getImage(getCodeBase(),"Images/Malt5.jpg");
pic6 = getImage(getCodeBase(),"Images/Malt6.jpg");
pic7 = getImage(getCodeBase(),"Images/Malt7.jpg");
//create graphics buffer, the size of the applet
Buffer = createImage(500,600);
g =Buffer.getGraphics();
}
public void start() {// Start the animation thread.
if (ThisThread == null) {
ThisThread = new Thread(this);
ThisThread.start();
}
}
public void stop() {
ThisThread = null; // Stop the animation thread.
}
public void run() {
while (Thread.currentThread() == ThisThread) {
repaint();// Update the display.
try {
Thread.currentThread().sleep(1000);
// Suspend the thread for the specified time (in milliseconds).
}
catch (InterruptedException e) {}
}
}
Image randomPicture()
{// Take a picture randomly
Image picture;
int algo=(int)(Math.random()*8);
switch(algo)
{
case 0: picture=pic0;
break;
case 1: picture = pic1;
break;
case 2: picture=pic2;
break;
case 3: picture=pic3;
break;
case 4: picture=pic4;
break;
case 5: picture=pic5;
break;
case 6: picture=pic6;
break;
default: picture= pic7;
}
return picture;//used in setThings method
}
public void setThings()
{
Color bgColor=new Color(0,150,0);
g.setColor(Color.lightGray);
g.fillRect(0,0,700,800);
Image pict = randomPicture();
g.drawImage(pict,20,20,this);
}
public void paint(Graphics g)
{
setThings();
g.drawImage (Buffer,30,30, this);
}
}
/*Comments
When executed:
C:\Java> javac AnimThread.java
C:\Java> appletviewer AnimThread.html
work perfectly.
C:\Java> javac -Xlint AnimThread.java
points a warning towards the class:
warning: [serial] serializable class AnimThread has no defini
tion of serialVersionUID
To set the problem, add
private static final long serialVersionUID = 1L;
*/
/* For the applet over a browser:
Animated pictures
*/
|