Using JCheckBox
A check box represents an option to the user that can be on or
off (or selected or unselected). It usually consists of two elements:
a small box which contains a tick if the option is selected, and a piece of text
that describes the option in question. The user clicks on the check box to select the
option; clicking again deselects it. Here is what a JTextBox looks like with the
default Swing look and feel:
In Java, you typically supply the text in the JCheckBox constructor:
public class DataOptionsFrame extends JFrame {
private JCheckBox quitOption = new JCheckBox("Quit on close");
...
}
Normally, you don't need any code to specifically handle the select/deselection:
Swing will handle this automatically. You will usually just need to check whether
or not the option is selected at some other strategic moment, e.g. when the
user OK's a dialog box etc. To do this, we call JCheckBox.isSelected().
In this example, we want to read whether or not the option is selected at the point of
the window being closed. So in our constructor of the frame,
we add a WindowListener, and read the check box option during
the windowClosed() method, which Swing will call for us when the window
is closed.
public DataOptionsFrame() {
super("Data options");
addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
if (quitOption.isSelected()) {
System.exit(0);
}
}
});
}
Using a JCheckBox to control component visibility
Occasionally, we do need to be notified when a JCheckBox is
selected or deselected, at the moment of selection/deselection. For example,
we might want some extra component to be made visible or editable in response to
the user selecting the option. For this, we can use an ActionListener.
The code will look something as follows:
JCheckBox showOps = new JCheckBox("Show extra options");
JPanel extraOptionsPanel = createExtraOptionsPanel();
...
showOps.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
extraOptionsPanel.setVisible(showOps.isSelected());
}
});
Further reading
To help you understand some of the above code, you may wish to read:
Events and listeners
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.