- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to select one item at a time from JCheckBox in Java?
JCheckBox
- A JCheckBox can extend 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 an ItemListener whenever the checkbox is changed.
- An isSelected() method is used to test if a checkbox is checked or not.
- By default, we can select all the checkbox items at a time, if we want to select only one item at a time by using ButtonGroup class.
Example
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JCheckBoxGroupTest extends JFrame { private ButtonGroup checkBoxGroup; private JCheckBox jcb1, jcb2, jcb3; private JPanel panel; public JCheckBoxGroupTest() { super("JCheckBoxGroup Test"); panel = new JPanel(new GridLayout(3,0)); jcb1 = new JCheckBox("India", true); jcb2 = new JCheckBox("England", false); jcb3 = new JCheckBox("Australia", false); checkBoxGroup = new ButtonGroup(); //add CheckBoxes to ButtonGroup checkBoxGroup.add(jcb1); checkBoxGroup.add(jcb2); checkBoxGroup.add(jcb3); panel.add(jcb1); panel.add(jcb2); panel.add(jcb3); add(panel); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) { new JCheckBoxGroupTest(); } }
Output
Advertisements