Java Reference
In-Depth Information
Tutorial: Finishing the Choice
You will now use your newfound looping skills to add the choice exemption values using only one add statement.
1.
In the EnterEmpInfo's getExmpChoice method, add a for loop (around the ExmpChoice.
add statement) to go from zero to ten, incrementing by one as follows:
for ( int ctr = 0; ctr <= 10; ctr = ctr + 1) {
}
2.
Change the add statement to add ctr as follows:
exmpChoice.add(ctr);
Notice the error stating that the add method expects a String and ctr is an int . We must convert ctr to a String .
We will use the String class's valueOf method.
3.
Change the add statement to the following:
exmpChoice.add(String. valueOf (ctr));
4.
Save EnterEmpInfo source and run as an application.
5.
Click the choice button.
The values 0 through 10 should be displayed.
6.
Select 3 for exemptions, enter 15 for pay rate, and click the tax amount button.
The tax amount displayed will be $52.50. Notice that the values are listed in the order they are added to the
choice. A good programmer/analyst would determine the most common number of exemptions and define that value
as the default for the choice. A default value is specified with the choice's select method.
7.
Click the Exit button and in the EnterEmpInfo's getExmpChoice method, after the for loop,
add the following statement:
exmpChoice.select("2");
Notice that the default value is simply passed to the select method. When the frame is displayed, the default value
will already be selected in the choice. If the drop-down menu is shown, the values will still appear in the order in
which they were added, and the default value will still be selected.
8.
Save EnterEmpInfo source and run as an application.
“2” should be displayed in the choice. The choice source code should look like the following:
private Choice getExmpChoice() {
if (exmpChoice == null ) {
exmpChoice = new Choice();
exmpChoice.setBounds( new Rectangle(195, 299, 46, 21));
for ( int ctr = 0; ctr <= 10; ctr = ctr + 1) {
exmpChoice.add(String. valueOf (ctr));
}
 
Search WWH ::




Custom Search