Create CheckBox in Java:
We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it. |
You can create a CheckBox using JCheckBox class that is nothing but an item that can be selected or deselected. A CheckBox generates one ItemEvent and one ActionEvent when it is clicked (selected or deselected). You can check whether a CheckBox is selected or not using the isSelected( ) method.
Java CheckBox Methods:
Method | Description |
---|---|
void setText(String) | Sets the text for the CheckBox. |
String getText( ) | Returns the CheckBox text. |
void setSelected(boolean) | Sets the state of the CheckBox to true for selected or false for unselected. |
boolean isSelected( ) | Gets the current state (checked or unchecked) of the CheckBox. |
void setBackground(Color) | Sets the background color. |
void setSelectedIcon (ImageIcon) | Set which image to display when CheckBox is selected. |
void setFocusable(boolean) | Draws a box around the component if it has focus (boolean is true) or not if the boolean is false. |
void setOpaque(boolean) | Sets background as transparent (boolean is false) or solid (boolean is true). |
Sample Code to Create CheckBox in Java:


Output:
When you tick the CheckBox and press the submit button it will return true in the output window otherwise false.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JCheckBox;
import javax.swing.JButton;
public class Checkbox extends JFrame implements ActionListener{
JButton btn;
JCheckBox jcb;
Checkbox(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
btn = new JButton();
btn.setText("submit");
btn.addActionListener(this);
jcb = new JCheckBox();
jcb.setText("JAVA Programming Language");
jcb.setFocusable(false);
jcb.setFont(new Font("Didot",Font.PLAIN,24));
this.add(btn);
this.add(jcb);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==btn) {
System.out.println(jcb.isSelected());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Checkbox();
}
}
Comments (No)