Page 760 - Introduction to Programming with Java: A Problem Solving Approach
P. 760
726 Chapter 17 GUI Programming—Component Layout, Additional GUI Components Methods
Here are the API headings and descriptions for the more popular JRadioButton methods: public boolean isSelected()
Returns true if radio button is selected and false otherwise. public void setSelected(boolean flag)
Makes radio button selected if argument is true. Does nothing if argument is false. public void setEnabled(boolean flag)
Makes radio button enabled or disabled. If enabled, it responds to mouse clicks.
public void addActionListener(ActionListener listener)
Adds a listener to the radio button.
We described these same methods in the JCheckBox section. Only one of them needs further attention— the setSelected method. To understand how setSelected works, you first need to understand fully how a user interacts with a radio button group. To select a radio button, a user clicks it. That causes the radio button to become selected and all other radio buttons in the group to become unselected. To programmati- cally select a radio button, you have the radio button call setSelected(true). That causes the radio button to become selected and all other radio buttons in the group to become unselected. As mentioned above, there is no way for a user to unselect a button. Likewise, there is no way for a program to unselect a button. That’s why calling setSelected(false) doesn’t do anything. It compiles and runs, but it doesn’t cause any buttons to change their selected status.
Apago PDF Enhancer
17.14 JcomboBox Component User Interface
A combo box allows a user to select an item from a list of items. Combo boxes are sometimes called drop- down lists because if a user clicks a combo box’s down arrow, a list of selection items drops down from the original display. Then, if a user clicks a selection from the drop-down list, the list disappears and only the selected item remains displayed. To get a better idea of what we’re talking about, see the select-a-day combo box in Figure 17.15.
Combo boxes and radio button groups are similar in that they both allow the user to select one item from a list of items. But a combo box takes up less space on the window. So if you have a long list of items to choose from, and you want to save space, use a combo box rather than a group of radio buttons.
Implementation
Creating a combo box component is a two-step process. First, instantiate an array of list options. Then, use the array as part of a JComboBox instantiation. Here’s the syntax for a JComboBox instantiation:
JComboBox <JComboBox-reference> = new JComboBox(<array-of-list-options>); The following example shows how we created the combo box in Figure 17.15:
String[] days =
{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
daysBox = new JComboBox(days);