A JCheckBox is a subclass of JToggleButton and it can be a small box that is either checked or unchecked. When we click on a JCheckBox, it changes from checked to unchecked or vice versa automatically. A JCheckBox can generate an ActionListener or ItemListener whenever the checkbox is changed. We can set the shortcut keys to a JCheckBox by using the setMnemonic() method.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCheckBoxShortCutKeyTest extends JFrame {
private JCheckBox checkBox;
public JCheckBoxShortCutKeyTest() {
setTitle("JCheckBoxShortCutKey Test");
checkBox = new JCheckBox("Check or Press ALT-C");
checkBox.setBorder(BorderFactory.createLineBorder(Color.lightGray));
checkBox.setMnemonic('C');
add(checkBox, BorderLayout.CENTER);
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "A Checkbox checked or pressed");
}
});
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) throws Exception {
new JCheckBoxShortCutKeyTest();
}
}Output
