Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^662) | Applets
public classFactInt extendsApplet implementsActionListener
{
public voidactionPerformed(ActionEvent event)
// Event handler method
{
int value;
value = Integer.parseInt(inputField.getText());
inputField.setText("");
outLabel.setText(value + " factorial is "+ factorial(value));
}
The main heading is just like that of an application, except the phrase extendsAppletimple-
mentsActionListenerfollows the class name. This phrase tells the compiler that we are work-
ing with an applet and not an application: Our class is derived from Applet. This applet also
implements the ActionListenerinterface, so we should expect a publicmethod actionPerformed
to be part of the class. The event handler takes a string as input, converts it to an integer value,
resets the text field to the empty string, and invokes the factorial function within the out-
put statement. The factorial function that follows is identical to the one from Chapter 13.
private intfactorial(int n)
// Assumption: n is not negative
{
if (n == 0)
return1; // Base case
else
return(n * factorial(n-1)); // General case
}
The next sections of code set up a button, a label, and a text input field.
// Set up a button, label, and input field
private TextField inputField;
private Label label;
private Label outLabel;
private Button button;
In an application, the method where execution begins is main. In an applet, execution be-
gins in the initmethod. The initializations that are carried out in mainin an application are
carried out in initin an applet.
public voidinit()
{
// Instantiate components
label = new Label("Enter an integer; click Enter.");
outLabel = new Label("Answer");
button = new Button("Enter");
button.addActionListener(this);

Free download pdf