Java Reference
In-Depth Information
Button Arrays
As specified in the requirements document, the Calculator application must have
a keypad complete with buttons for the numbers 0 through 9, a decimal point,
an equal sign, and four arithmetic operators (addition, subtraction, multiplica-
tion, and division).
Because the Calculator application requires 16 separate buttons to create the
keypad, it makes sense to use an array. You may remember that an array is a list
that employs a single but inclusive storage location to hold data of the same type
with the same identifier name. Using a button array will allow you to use the
same code for multiple buttons and will facilitate searching for which button was
clicked.
Creating the Keypad
Figure 6-14 displays the code to construct and label the keypad buttons, as
well as the method to establish the GridLayout to organize the buttons. As
shown in lines 82 and 83, in the case of the Button array named keys, using an
array allows the code to construct and label the numeric buttons using a for
loop, with only two lines of code instead of ten: one line of code for the for state-
ment (line 82) and another for the construction (line 83).
81
// construct and assign captions to the Buttons
(
82
for int
i=0; i<=9; i++
)
83
keys
[
i
]
=
new
Button
(
String
.valueOf
(
i
))
;
84
85
keys
[
10
]
=
new
Button
(
"/"
)
;
86
keys
[
11
]
=
new
Button
(
"*"
)
;
87
keys
[
12
]
=
new
Button
(
"-"
)
;
88
keys
[
13
]
=
new
Button
(
"+"
)
;
89
keys
[
14
]
=
new
Button
(
"="
)
;
90
keys
[
15
]
=
new
Button
(
"."
)
;
91
92
// set Frame and keypad layout to grid layout
93
setLayout
(
new
BorderLayout
())
;
94
keypad.setLayout
(
new
GridLayout
(
4,4,10,10
))
;
95
FIGURE 6-14
The for loop uses an integer, i, to increment through the 10 digits and assign
numeric labels to the individual buttons, one at a time. Buttons receive their
labels as arguments to the Button method. Recall that Java's valueOf() method
converts the numeric value of i to a String. Therefore, in line 83, the argument in
the Button constructor becomes the label of the button itself. Because line 83 is
the only code in the for loop, block braces are unnecessary; however, indenting
line 83 makes the code easier to read and understand.
Lines 85 through 90 explicitly assign the operator, equal sign, and decimal
point labels for the other buttons. Line 93 sets the layout of the Frame to
BorderLayout, and line 94 sets the layout of the keypad Panel to GridLayout with
four rows and four columns.
Search WWH ::
Custom Search