Controls and layout managers
Components
Check boxes
A frame with a check box
Common constructors of the JCheckBox class
Constructor | Description |
---|---|
JCheckBox(String) | Creates an unselected check box with a label that contains the specified string. |
JCheckBox(String, boolean) | Creates a check box with a label that contains the specified string. If the boolean value is true, the check box is selected. |
Some methods that work with check boxes
Method | Description |
---|---|
isSelected() | Returns a true value if the check box is selected. |
setSelected(boolean) | Checks or unchecks the check box depending on the boolean value. |
addActionListener(ActionListener) | Adds an action listener to the check box. |
Code that creates the check box
private JCheckBox mailingCheckBox; mailingCheckBox = new JCheckBox("Add to mailing list", true); mailingCheckBox.addActionListener(this); add(mailingCheckBox);
Code that checks the status of the check box
boolean addToList = mailingCheckBox.isSelected();
An actionPerformed method for the check box
public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == mailingCheckBox) { if (mailingCheckBox.isSelected()) addressTextArea.setEnabled(true); else addressTextArea.setEnabled(false); } }