Back to Applets page
Click in the boxes below, select all and copy to grab the applet
HTML listing:
<HTML> <HEAD> <TITLE>Listing 10.8</TITLE> </HEAD> <BODY BGCOLOR=WHITE> <APPLET CODEBASE="classes" CODE="Applet8.class" WIDTH=300 HEIGHT=100> </APPLET> </BODY> </HTML>
Applet listing:
import java.awt.*; import java.applet.*; import java.awt.image.*; public class Applet8 extends Applet implements Runnable { int cardWidth=43,cardHeight=61,thisPos; Image winScratch,playingCards,currImg; Graphics gScratch; Thread runner; Button startStop; boolean isRunning = true; public void init() { winScratch = createImage(this.size().width,this.size().height); gScratch = winScratch.getGraphics(); setBackground(Color.white); playingCards = getImage(getCodeBase(),"cards.gif"); startStop = new Button("Stop"); add(startStop); } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { runner = null; } public void run() { int randomCard,cardPos; ImageFilter cardFilter; ImageProducer cardProducer; while (isRunning) { try { Thread.sleep(2000); } catch (InterruptedException e) { } thisPos = (int)(java.lang.Math.random() * 200); randomCard = (int)(java.lang.Math.random() * 52); cardPos = (randomCard*cardWidth)+1; cardFilter = new CropImageFilter(cardPos,1,cardWidth,cardHeight); cardProducer = new FilteredImageSource(playingCards.getSource(),cardFilter); currImg = createImage(cardProducer); repaint(); } } public void paint(Graphics g) { if (currImg != null && isRunning) { gScratch.setColor(this.getBackground()); gScratch.fillRect(0,0,this.size().width,this.size().height); gScratch.setColor(Color.black); gScratch.drawImage(currImg,thisPos+3,32,this); gScratch.drawRoundRect(thisPos+1,30,cardWidth+2,cardHeight+2,5,5); g.drawImage(winScratch,0,0,this); } } public final void update(Graphics g) { paint(g); } public boolean action(Event e, Object arg) { if (e.target instanceof Button) { if (isRunning) { isRunning = false; startStop.setLabel("Start"); stop(); } else { isRunning = true; startStop.setLabel("Stop"); start(); } return true; } return false; } }