Java Reference
In-Depth Information
}
else if (actionCommand.equals("Clear"))
story.setText("");
else
story.setText("Unexpected error.");
}
private int getLineCount()
{
String storyString = story.getText();
int count = 0;
for ( int i = 0; i < storyString.length(); i++)
if (storyString.charAt(i) == '\n')
count++;
return count + 1; //The last line has no '\n'.
}
}
39.
We made the text field an instance variable because we needed to refer to it in
the definition of the method actionPerformed . On the other hand, the only
direct reference we had to the buttons was in the constructor. So, we need names
for the buttons only in the constructor definition.
40.
The GUI would try to add the string "Enter numbers here." as if it were a
string for a number. This will cause a NumberFormatException to be thrown and
the string "Error: Reenter Number." would be displayed in the text field.
41.
Every time the user clicks the addition button, the following assignment is executed:
result = result + stringToDouble(ioField.getText());
So, the number in the text field is added to the total as many times as the user
clicks the addition button. But, the value in the text field is the running total, so
the running total is added to itself. Thus, the running total is added to the total
as many times as the user clicks the addition button.
Let's say that the user starts the GUI, types in 10 , and clicks the addition button. That
adds 10 to result , so the value of result is then 0 plus 10 , which is 10 , and 10 is
displayed. Now the user clicks the addition button a second time. That adds 10 to
result again, so the value of result is 10 plus 10 , which is 20 , and 20 is displayed.
Next the user clicks the addition button a third time. This time, 20 is in the text field,
and so it is added to result , which is also 20 . Thus, the value of result is now 40 ,
and 40 is displayed. Note that it is always the number in the text field that is added in.
42.
The two calculator windows are completely independent. Each has its own instance
variable result , which has no effect on the other's instance variable result .
43.
If you click the close-window button in either calculator window, the entire program
ends because that causes an invocation of System.exit . There is no invocation of
Search WWH ::




Custom Search