Java Reference
In-Depth Information
96
for ( int i=7; i<=10; i++ ) // 7, 8, 9, divide
97
keypad.add ( keys [ i ]) ;
98
99
for ( int i=4; i<=6; i++ ) // 4, 5, 6
100
keypad.add ( keys [ i ]) ;
101
102
keypad.add ( keys [ 11 ]) ; // multiply
103
104
for ( int i=1; i<=3; i++ ) // 1, 2, 3
105
keypad.add ( keys [ i ]) ;
106
107
keypad.add ( keys [ 12 ]) ; // subtract
108
109
keypad.add ( keys [ 0 ]) ; // 0 key
110
111
for ( int i=15; i>=13; i-- )
112
keypad.add ( keys [ i ]) ; // decimal point, =, add (+) keys
113
FIGURE 6-16
The for loop in line 96 adds the row of buttons in the first row of the grid
(Buttons 7, 8, 9, and /). The for loop in line 99 adds the numeric buttons in the
second row of the grid (Buttons 4, 5, and 6). Line 102 adds the multiplication
button (*) to the second row. The for loop in line 104 adds the numeric buttons
to the third row of the grid (Buttons 1, 2, and 3). Line 107 adds the subtraction
(-) button to the third row.
Finally, the bottom row of the grid is created as line 109 adds the zero button
(0), and the for loop in line 111 adds the decimal point (.), the equal sign (=),
and the addition (+) buttons. Notice that line 111 uses the decrement operator
to move backward from 15 to 13 in order to add the Buttons in the correct order
in the last row.
Figure 6-17 displays the code to add the ActionListener to each of the
Buttons. The for loop in line 114 goes from 0 to the end of the array, using the
length property of the array. It is better to use the length property than to enter
the actual numeric length of 16 because if you wish to add more buttons to the
calculator, the search will execute accurately without having to change the num-
ber in that line of code. Line 115 uses a self-referential, this, to reference the keys
array and add the ActionListener to each Button. Recall that the keyword, this,
refers back to its own control — in this case, the keys array.
114
for ( int i=0; i<keys.length; i++ )
115
keys [ i ] .addActionListener ( this ) ;
116
117
add ( lcd, BorderLayout .NORTH ) ;
118
add ( keypad, BorderLayout .CENTER ) ;
119
FIGURE 6-17
Line 117 adds the lcd TextField to the North region of the BorderLayout, and
line 118 adds the keypad Panel to the Center region of the BorderLayout.
Search WWH ::




Custom Search