Page 757 - Introduction to Programming with Java: A Problem Solving Approach
P. 757

                   Figure 17.13 Example that illustrates JCheckBox’s setSelected and setEnabled methods
changes to the standard-configuration check box values. In Figure 17.13’s left window, note that the check boxes are gray. We say that they’re grayed out. That’s the standard GUI way of telling the user that some- thing is disabled.
Check Box Listeners
With a JButton component you’ll almost always want an associated listener. But with a JCheckBox component, you may or may not want an associated listener. If you have a check box with no listener, then the check box simply serves as an input entity. If that’s the case, then the check box’s value (checked or unchecked) would typically get read and processed when the user clicks a button. On the other hand, if you want something to happen immediately, right when the user selects a check box, then add a listener to the check box component. Suppose you have a Green Background check box. If you want the window’s back- ground color to change to green right when the user clicks the check box, add a listener to the check box. The syntax for adding a listener to a JCheckBox component is the same as the syntax for adding a listener to a JButton component. Provide a listener that implements the ActionListener interface and then add the listener to the JCheckBox component by calling addActionListener.
Be aware that Sun provides an alternative listener interface for the JCheckBox component—the ItemListener interface. An ActionListener listens for the user clicking on a check box. An ItemListener listens for a state change; that is, it listens for a check box changing from selected to unselected or vice versa. A check box state change is triggered when a user clicks the check box or when a program calls setSelected with a value that’s different from the current value. Since the ActionListener interface is the preferred interface for most situations, we’ll stick with it when imple- menting JCheckBox listeners. When we get to the JRadioButton and JComboBox components in the next sections, we’ll continue to use the ActionListener interface, not the ItemListener interface.
Installation-Options Example
It’s now time to put these check box concepts into practice by showing you some code. Look back at the installation-options windows in Figure 17.13. In Figure 17.14, we provide the listener code associ- ated with those windows. Let’s walk through the code. In the if statement’s condition, we check
Apago PDF Enhancer
17.12 JcheckBox Component 723


























































































   755   756   757   758   759