Back to Applets page
Click in the boxes below, select all and copy to grab the applet
HTML listing:
<HTML> <HEAD> <TITLE>Listing 6.2</TITLE> </HEAD> <BODY BGCOLOR=WHITE> <APPLET CODEBASE="classes" CODE="Applet2.class" WIDTH=500 HEIGHT=100> </APPLET> </BODY> </HTML>
Applet listing:
import java.awt.*; import java.applet.Applet; import java.awt.Font; public class Applet2 extends Applet { TextField guessField = new TextField(5); int nextGuess = -1; int targetNum = (int)(java.lang.Math.random() * 100)+1; Font f = new Font("TimesRoman",Font.BOLD,24); public void init() { setBackground(Color.white); add(guessField); } public void paint(Graphics g) { String numberStatus = nextGuess + " is correct"; g.setFont(f); if (nextGuess != targetNum) { if (nextGuess < 1) { numberStatus = "Guess a number between 1 and 100"; } else { if (nextGuess < targetNum) { numberStatus = nextGuess + " is too low"; } else { numberStatus = nextGuess + " is too high"; } } } g.drawString(numberStatus, 20, 60); } public boolean action(Event e, Object arg) { if (e.target instanceof TextField) { try { nextGuess = Integer.parseInt(guessField.getText()); } catch (NumberFormatException x) { nextGuess = -1; } repaint(); return true; } return false; } }