Back to Applets page
Click in the boxes below, select all and copy to grab the applet
HTML listing:
<HTML> <HEAD> <TITLE>Listing 6.7</TITLE> </HEAD> <BODY BGCOLOR=WHITE> <APPLET CODEBASE="classes" CODE="Applet7.class" WIDTH=500 HEIGHT=100> </APPLET> </BODY> </HTML>
Applet listing:
import java.awt.*; import java.applet.Applet; import java.awt.Font; public class Applet7 extends Applet { int appNum = (int)(java.lang.Math.random() * 3)+1; Font f = new Font("TimesRoman",Font.BOLD,16); CheckboxGroup userCheckbox; boolean firstTime = true; String userChoice; public void init() { setBackground(Color.white); userCheckbox = new CheckboxGroup(); add(new Checkbox("Rock",userCheckbox,false)); add(new Checkbox("Scissors",userCheckbox,false)); add(new Checkbox("Paper",userCheckbox,false)); } public void paint(Graphics g) { int userNum; String appChoice; g.setFont(f); if (firstTime) { g.drawString("Play Rock, Scissors, Paper with me!",20,60); firstTime = false; } else { switch(appNum) { case 1: appChoice = "Rock"; break; case 2: appChoice = "Scissors"; break; case 3: appChoice = "Paper"; break; default: appChoice = "Error"; } switch (userChoice.charAt(0)) { case 'R': userNum = 1; break; case 'S': userNum = 2; break; case 'P': userNum = 3; break; default: userNum = 0; } if (appNum == userNum) { g.drawString("Tie game--let's play again.", 20, 60); } else { if ((userNum==1 && appNum==3) || (userNum==2 && appNum==1) || (userNum==3 && appNum==2)) { g.drawString("I win! I picked "+appChoice+".", 20, 60); } else { g.drawString("You win! I picked "+appChoice+".", 20, 60); } } g.drawString("Reload the page to play another game",20,80); } } public boolean action(Event e, Object arg) { if (e.target instanceof Checkbox) { userChoice = userCheckbox.getCurrent().getLabel(); repaint(); return true; } return false; } }