Java Reference
In-Depth Information
Tutorial: Working with an ItemEvent and States
Until now, we've glossed over events by simply saying they are passed to the itemStateChanged (or actionPerformed)
methods. Events are objects and have useful methods and properties. For example, we have added the ItemListener to
three checkboxes. Wouldn't it be nice to be able to tell which checkbox has been clicked? Well, it just so happens that
the ItemEvent's getSource method will return the object that was clicked. Alternatively, checkboxes have a method
called getState that returns a Boolean value. If the checkbox is checked, the state value is true, and it is false if not
checked. We will show how to use both methods to determine which checkbox has been selected.
1.
Replace the source code in the CBTestApp itemStateChanged method with the following
nested ifs:
if (empAppCB == e.getSource()){
System.out.println("Employee App was selected!");}
else if (shipAppCB == e.getSource()){
System.out.println("Shipment App was clicked!");}
else if (sortAppCB == e.getSource()){
System.out.println("Sorting App was clicked!");}
The earlier if examples had comparisons between primitive variables and fixed constants. Notice that this time
we are comparing the reference variable empAppCB to the object returned by the ItemEvent's getSource method.
When the objects match, the appropriate message will be displayed and no other checkboxes will be tested.
2.
Save the source and run CBTestApp as a Java application.
3.
Click the shipAppCB checkbox, then empAppCB, then sortAppCB, then the Exit button.
Notice that the appropriate message was displayed each time. Now we'll use the getState method in the if
conditions to determine which checkbox is selected.
4.
Comment out the code in the itemStateChanged method, add the following nested ifs, and
run CBTestApp:
if (empAppCB.getState())
System.out.println("Employee App was selected!");
else if (shipAppCB.getState())
System.out.println("Shipment App was clicked!");
else if (sortAppCB.getState())
System.out.println("Sorting App was clicked!");
5.
Click the shipAppCB checkbox, then empAppCB, then sortAppCB, then the Exit button.
Again, the appropriate message is displayed each time.
Tutorial: VE and Checkboxes
1.
In Tutorials/c6, create a new Java visual class called AppOptions that defines:
c6.UsefulFrame as the superclass;
an ItemListener interface; and
main and inherited abstract method stubs.
 
Search WWH ::




Custom Search