Java Reference
In-Depth Information
The Choice Component
One way that we could cut down on data entry errors (like an incorrect value for exemptions) is to always check the
user-entered values and make sure it is numeric. However, an even better technique is to provide a “list” of correct
values and only allow users to select and submit values from the list. A Choice component looks like a text field with a
small rectangular button on the right. When the button is clicked, a drop-down menu containing text is displayed. The
text displayed in the drop-down menu can be defined in the application and when a user clicks one of the values, the
application can retrieve the selected value.
Because there are a limited number of correct values, the exemptions value is a good candidate for a choice.
Other data, for instance pay rate, are not good candidates because there are thousands of correct values (e.g., 10.50,
10.75, etc.) We will delete the exemptions text field and add a Choice component.
1.
In Visual Editor, click the exemptions text field and press the Delete key.
A statement in the actionPerformed method will be flagged with an error because it references the exemptions
text field. We will fix this (a little later) by replacing the statement with one that will work with the choice we are
about to add.
In the component palette, click on the AWT Choice component then click on the frame
location where the exemptions text field was.
2.
3.
Specify the name as exmpChoice and then change exmpChoice:
So it aligns with the text fields and exmpLbl
Resize to 46, 21
We now need to put some values into the choice's drop-down menu. Values are added to a choice with the
component's add method.
4.
At the end of the getExmpChoice method, insert the following statement that adds the
value zero to the drop-down menu:
exmpChoice.add("0");
5.
In the actionPerformed method, replace the flagged statement that retrieved the
exemption text field value with the following (which retrieves the choice's value):
String exmp = exmpChoice.getSelectedItem();
Let's test and make sure the value appears.
6.
Save the source and run the application.
When the frame is displayed, the value 0 should appear in the choice.
7.
Click on the choice field button.
A very small drop-down menu with the single value 0 should be displayed.
8.
Press the exit button to end the application.
Obviously, the choice needs more values. We could add 10 more add statements for the values one through ten,
but this would not be very efficient. Instead, we will define a loop so that the same add method will be performed
11 times with a different value each time.
 
Search WWH ::




Custom Search