The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > JCheckBox  [4 examples]

e752. Creating a JCheckbox Component

By default, the state of the checkbox is off; to change the state, see e753 Getting and Setting the State of a JCheckbox Component. Also by default, the checkbox is left-justified and vertically centered. The methods to control the text alignment are identical to those of a JButton; see e748 Moving the Label/Icon Pair in a JButton Component.
    // Create an action
    Action action = new AbstractAction("CheckBox Label") {
        // This method is called when the button is pressed
        public void actionPerformed(ActionEvent evt) {
            // Perform action
            JCheckBox cb = (JCheckBox)evt.getSource();
    
            // Determine status
            boolean isSel = cb.isSelected();
            if (isSel) {
                // The checkbox is now selected
            } else {
                // The checkbox is now deselected
            }
        }
    };
    
    // Create the checkbox
    JCheckBox checkBox = new JCheckBox(action);

 Related Examples
e753. Getting and Setting the State of a JCheckbox Component
e754. Adding an Icon to the Label of a JCheckBox Component
e755. Customizing the Icons in a JCheckBox Component

See also: Actions    JButton    JComboBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Keystrokes and Input Maps    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.