3.15 The Integer, Double, and Other Wrapper Classes
A wrapper class “wraps” the value of a primitive type, such as double or int, into an object.
The parseInt, parseDouble, and valueOf methods are static and are called using the Integer or Double class name and the dot notation. The parse methods convert a String to a primitive type, and the valueOf methods convert a String to a wrapper object.
12.7 Radio Buttons and Checkboxes
Radio buttons prompt users to select only one among many mutually exclusive buttons.
Check boxes enable users to select multiple buttons at one time and if the user clicks on a selected button, that button will be deselected.
import javax.swing.JRadioButton; import javax.swing.JCheckBox;
Selecting or deselecting radio buttons and checkboxes fire an ItemEvent. To receive this event, our event handler needs to implement the ItemListener interface.
Create a new RadioButtonHandler and register JButton red, blue, and green with an Itemlistener respectively in line 46,47,48. Then create a private method RadioButtonHandler which implements ItemListener class. The getSource method is used to detect the receiver of an action. In the case in line 58 and 59, if the receiver of a click is the JButton red, the JButton red will turn to the color red.
12.9 Combo Boxes
- The user chooses from a list of countries and we then display a typical food from the selected country.
A JComboBox fires an ItemEvent, so the event handler must implement the ItemListener interface, and thus, provide the itemStateChanged method.
private JComboBox<String> countries;
Declare and instantiate the instance variable, foods, as an array of ImageIcons (lines 15–20). The foods array stores images of the food samplings in the same order as the countries in our list. The instance variable countryList, an array of Strings declared and initialized at lines 12–13, holds the names of the countries to be displayed in the list.
countries = new JComboBox<String>(countryList);
We initiate an ItemListnerHandler called ilh in line 41 and add an action handler on each element inside countryLists array.
By using getSelectedIndex(), the event handler can determine which item in the JCombo countries has been selected. Then the JLabel foodImage will show a photo corresponds to the selected country in the countryList.
Conclusion
I learned how to implement radiobutton(mutually exclusive choices), checkbox(multi-selected choices), and combo(scroll down lists). We have to register an event handler on all the choice so that whenever a choice is selected, the event handler can detect which item is selected and do the following required job.
Work Cited
Anderson, J. and Franceschi, H. (2016). Java illuminated. 1st ed. Burlington, MA: Jones & Bartlett Learning.