Java Reference
In-Depth Information
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 us 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 System.exit in Display 17.19, but the following ensures that a
System.exit that is in some library class will be invoked:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Programming Projects
Visit www.myprogramminglab.com to complete select exercises online and get instant
feedback.
1. Design and code a Swing GUI to translate text that is input in English into Pig
Latin. You can assume that the sentence contains no punctuation. The rules for
Pig Latin are as follows:
VideoNote
Solution to
Programming
Project 17.1
a. For words that begin with consonants, move the leading consonant to the end
of the word and add “ay.” Thus, “ball” becomes “allbay”; “button” becomes
“uttonbay”; and so forth.
b. For words that begin with vowels, add “way” to the end of the word. Thus,
“all” becomes “allway”; “one” becomes “oneway”; and so forth.
 
Search WWH ::




Custom Search