Program Trace
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class SquaredNumbers extends Applet implements ActionListener
{
public Button bSquare;
public TextField startNumInput, endNumInput;
public Label title;
public int startNum, endNum;
public int mode;
public void init( )
{
title = new Label("THE SQUARE MACHINE");
bSquare = new Button("COMPUTE SQUARES");
startNumInput = new TextField(8);
endNumInput = new TextField(8);
add(title); add(bSquare);
add(startNumInput);
add(endNumInput);
bSquare.addActionListener(this);
startNum = 0; endNum = 0; mode = 0;
}
public void paint(Graphics g)
{
if (mode == 0)
g.drawString("Enter starting and ending values and press the button",
10, 150);
else if (mode == 1)
g.drawString("Input is invalid -- check and renter", 10, 150);
else
printSquares(g, startNum, endNum);
}
public void actionPerformed(ActionEvent e)
{
startNum = Integer.parseInt(startNumInput.getText());
endNum = Integer.parseInt(endNumInput.getText());
showStatus("Button Pushed");
if (startNum <= endNum) mode = 2; else mode = 1;
repaint();
}
// Here is the code that prints the squares of the entered numbers --
// this contains the loop
void printSquares(Graphics g, int num1, int num2)
{
int i, yLoc;
g.setColor(Color.yellow);
g.fillRect(0, 0, getSize().width, getSize().height);
g.setColor(Color.black);
yLoc = 65;
for (i = num1; i <= num2; i = i + 1)
{
g.drawString("The square of " + i + " is " + i * i, 25, yLoc);
yLoc = yLoc + 15;
}
}
}