Issue
I been searching all the websites and also in youtube to find out how to use to use one jcheckbox in my project.
I want to function this checkbox as enable and disable, also i want to use to inter single data into database table
Solution
JCheckBox
is quite a simple component.
You can use one of its constructors to create a JCheckBox
object.
You can use isSelected()
method to check whether it is ticked or not.
You can use setSelected(boolean)
method to tick or untick it programmatically.
You can use addActionListener()
method to register a listener to get notifications when user tick it or untick it. (There are few other listeners as well.)
Simple sample program:
import javax.swing.*;
import java.awt.GridLayout;
public class SimpleCheckBox
{
public static void main(String[] args)
{
JCheckBox checkBox = new JCheckBox("Active");
checkBox.addActionListener(e -> System.out.println("User clicked the check box"));
JButton print = new JButton("Print status");
print.addActionListener(e -> System.out.println("Selected: " + checkBox.isSelected()));
JButton select = new JButton("Select");
select.addActionListener(e -> checkBox.setSelected(true));
JButton deselect = new JButton("Deselect");
deselect.addActionListener(e -> checkBox.setSelected(false));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new GridLayout(4, 1));
f.getContentPane().add(checkBox);
f.getContentPane().add(print);
f.getContentPane().add(select);
f.getContentPane().add(deselect);
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}
Answered By - Prasad Karunagoda
Answer Checked By - Gilberto Lyons (JavaFixing Admin)