jCheckbox using to display a state to the user and it inherits jToggleButton class. It is a part of Java Swing package and JCheckBox can be selected or deselected.
What is the difference between jCheckBox and jRadio Button.? This article will help you to know everything and configure jCheckBox and jRadio Button.
JCheckBox
When we need to display or get more than one user options, we can use this. Add as many jCheckbox you want to the jFrame, Edit the text accordingly and call the selected jCheckbox variables.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text = "Selected Values : ";
if (jCheckBox1.isSelected()){
text=text+" "+jCheckBox1.getText();
}
if (jCheckBox2.isSelected()){
text=text+", "+jCheckBox2.getText();
}
if (jCheckBox3.isSelected()){
text=text+" "+jCheckBox3.getText();
}
if (jCheckBox4.isSelected()){
text=text+" "+jCheckBox4.getText();
}
JOptionPane.showMessageDialog(rootPane, text);
}
jRadio Button
jRadio Button is providing option to user to choose one item from a list rather than multiple items available from check boxes.
Drag and drop a panel onto your form. Then locate the Radio Button control in the NetBeans palette.
Drag a Radio button onto your new palette. It should look like this:
By default the radio buttons will allow to select multiple items. Use “ButtonGroup”, it will help you to choose single item only. Our groupButton method adds radio buttons to the ButtonGroup object, with the use of the add method:
ButtonGroup bg1 = new ButtonGroup( );
bg1.add( radio_button_name );
Below describes the submit button code for buttonGroup configure to select one item and it will display the selected item from the list while clicking the submit button.
private void jSubmitActionPerformed(java.awt.event.ActionEvent evt) {
ButtonGroup bg1 = new ButtonGroup( );
bg1.add(jRadioButton1);
bg1.add(jRadioButton2);
bg1.add(jRadioButton3);
jRadioButton1.setActionCommand(jRadioButton1.getText());
jRadioButton2.setActionCommand(jRadioButton2.getText());
jRadioButton3.setActionCommand(jRadioButton3.getText());
JOptionPane.showMessageDialog(rootPane,bg1.getSelection().getActionCommand()) ;
}
Button Group
In case if you are offering to select on one state or option from a user from a perticular group of jCheckboxes. This “buttonGroup” feature mainly using to provide users to choose one item at a time.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jCheckBox1.setActionCommand(jCheckBox1.getText());
jCheckBox2.setActionCommand(jCheckBox2.getText());
jCheckBox3.setActionCommand(jCheckBox3.getText());
String text=buttonGroup1.getSelection().getActionCommand();
// To Display the selected checkbox
JOptionPane.showMessageDialog(rootPane, text);
}
Hope you this is useful. Thank you