Page 756 - Introduction to Programming with Java: A Problem Solving Approach
P. 756
722 Chapter 17 GUI Programming—Component Layout, Additional GUI Components
Implementation
To create a check box component, call the JCheckBox constructor like this:
JCheckBox <JCheckBox-reference> = new JCheckBox(<label>,<selected>);
The label argument specifies the text that appears at the right of the check box’s square. If the label argu- ment is omitted, then no text appears at the right of the check box’s square. The selected argument specifies whether the check box is selected initially—true means selected, false means unselected. If the selected argument is omitted, then the check box is initially unselected.
Here’s how the check box was created in the license-agreement window:
confirmBox = new JCheckBox("I accept the terms of this agreement.", true);
Methods
Here are the API headings and descriptions for the more popular JCheckBox methods: public boolean isSelected()
Returns true if the check box is selected and false otherwise. public void setVisible(boolean flag)
Makes the check box visible or invisible.
public void setSelected(boolean flag)
Makes the check box selected or unselected.
Apago PDF Enhancer
public void setEnabled(boolean flag)
Makes the check box enabled or disabled.
public void addActionListener(ActionListener listener)
Adds a listener to the check box.
The isSelected and setVisible methods are straightforward, but the other three methods need further explanation. Let’s start with setSelected. Why might you want to call setSelected and ad- just the selection status of a check box? Because you might want one user input to impact another user input. For example, in Figure 17.13, the user’s selection of standard versus custom4 should impact the check box selections. More specifically, if the user selects the Standard option, the check box selections should go to their “standard” settings. As you can see in Figure 17.13’s left window, the standard settings for the check boxes are the top two selected and the bottom two unselected. To have your program select the top two check boxes, those two check boxes should call setSelected(true). To have your program unselect the bottom two check boxes, those two check boxes should call setSelected(false).
To have your program disable a check box, the checkbox should call setEnabled(false). Why might you want to call setEnabled(false) and disable a check box? Because you might want to keep the user from modifying that box’s value. For example, if the user selects the Standard option as shown in Figure 17.13’s left window, the check box selections should be set to their standard settings (as explained above), and then each check box should call setEnabled(false). That way, the user cannot make
4 The Standard and Custom circles at the top of Figure 17.13 are called radio buttons. We’ll describe JradioButton components in the next section.