JRadioButton in Java
JRadioButton is a GUI component in Java Swing that represents a button that can be selected or deselected by the user. It is used in scenarios where the user needs to select one option from a set of options.
Here's an example of how to create a JRadioButton in Java:
javaimport javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class MyRadioButtonExample
{
public static void main(String[] args) {
JFrame frame = new JFrame("JRadioButton Example");
JPanel panel = new JPanel();
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
panel.add(radioButton1);
panel.add(radioButton2);
frame.add(panel);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this example, we first create a JFrame and a JPanel. We then create two JRadioButton objects, radioButton1
and radioButton2
, with labels "Option 1" and "Option 2" respectively. We add these JRadioButtons to the JPanel, and then add the JPanel to the JFrame.
When the user clicks on one of the radio buttons, the button becomes selected and the other radio buttons in the group become deselected. You can group radio buttons by putting them in a ButtonGroup object.
javaimport javax.swing.ButtonGroup;
// ...
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
In this example, both radio buttons belong to the same group, buttonGroup
. When one radio button is selected, the other radio button in the group is automatically deselected.
Comments
Post a Comment