This example demonstrate a various way to create JCheckBox
component. Here you can also see how the handle an event when the checkbox is clicked by user.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
public class CheckBoxDemoCreate extends JFrame {
public CheckBoxDemoCreate() throws HeadlessException {
initialize();
}
private void initialize() {
setSize(500, 500);
setTitle("JCheckBox Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
// Creating checkbox with text label
JCheckBox checkBoxA = new JCheckBox("Selection A");
// Creating checkbox with text label a set the state into checked
JCheckBox checkBoxB = new JCheckBox("Selection B", true);
// Creating checkbox with text label and a default unselected image icon
ImageIcon icon = new ImageIcon(
Objects.requireNonNull(
this.getClass().getResource("/images/lightbulb_off.png")));
JCheckBox checkBoxC = new JCheckBox("Selection C", icon);
// Add action listener to listen for click and change the image icon
// respectively
checkBoxC.addActionListener(e -> {
JCheckBox checkBox = (JCheckBox) e.getSource();
if (checkBox.isSelected()) {
checkBox.setIcon(new ImageIcon(
Objects.requireNonNull(
this.getClass().getResource("/images/lightbulb.png"))));
// Perform other actions here!
} else {
checkBox.setIcon(new ImageIcon(
Objects.requireNonNull(
this.getClass().getResource("/images/lightbulb_off.png"))));
// Perform other actions here!
}
});
getContentPane().add(checkBoxA);
getContentPane().add(checkBoxB);
getContentPane().add(checkBoxC);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CheckBoxDemoCreate().setVisible(true));
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024