JCheckBox Class
Package: javax.swing
The JCheckBox
class creates a check box that the user can click (select) to check or clear. Check boxes usually let the user specify a Yes
or No
setting for an option. Figure 5-3 shows a frame with three check boxes.
Figure 5-3
Constructors
Constructor |
Description |
|
Creates a new check box that is initially unchecked. |
|
Creates a new check box that displays the specified text. |
|
Creates a new check box with the specified text. The |
Methods
Method |
Description |
|
Adds an |
|
Adds an |
|
Gets the text displayed by the check box |
|
Returns |
|
Checks the check box if the parameter is |
|
Sets the check box text |
|
Sets the tooltip text that’s displayed if the user rests the mouse over the check box for a few moments |
Here’s an example that creates a check box:
JCheckbox pepperoni;
pepperoni = new JCheckBox(“Pepperoni”);
To create a check box that is initially checked, call the constructor like this:
JCheckbox pepperoni;
pepperoni = new JCheckBox(“Pepperoni”, true);
You can test the state of a check box by using the isSelected
method:
if (pepperoni.isSelected())
{
// code to execute if pepperoni is selected
}
You can set the state of a check box by calling its setSelected
method:
pepperoni.setSelected(false);
The preceding line clears the check box referred to by the pepperoni
variable.
An action event is generated whenever the user clicks a check box to change its state.
An item event is generated whenever the state of the check box is changed, whether as a result of being clicked by the user or because the program called the setSelected
method.
Suppose that your pizza restaurant has anchovies on the menu, but you want to discourage your customers from actually ordering them. Here’s an actionPerformed
method from an action listener that displays a message if the user ordered anchovies:
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == anchovies)
{
JOptionPane.showMessageDialog(anchovies,
“Yuck! Anchovies are disgusting!”,
“Yuck!”,
JOptionPane.WARNING_MESSAGE);
anchovies.setSelected(false);
}
}