Java jradiobutton basic tutorial and examples

Sure! Here's a basic tutorial and example of using JRadioButton in Java:

A JRadioButton is a swing component that represents a button that can be either selected or unselected. JRadioButton components are often used in groups to create a set of mutually exclusive options, where only one option can be selected at a time.

Here's an example of creating a JRadioButton:

refer to‮gi:‬iftidea.com
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class RadioButtonExample extends JFrame {
  
  public RadioButtonExample() {
    super("Radio Button Example");
    JPanel panel = new JPanel();
    JRadioButton radioButton1 = new JRadioButton("Option 1");
    JRadioButton radioButton2 = new JRadioButton("Option 2");
    JRadioButton radioButton3 = new JRadioButton("Option 3");
    ButtonGroup buttonGroup = new ButtonGroup();
    buttonGroup.add(radioButton1);
    buttonGroup.add(radioButton2);
    buttonGroup.add(radioButton3);
    panel.add(radioButton1);
    panel.add(radioButton2);
    panel.add(radioButton3);
    add(panel);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
    new RadioButtonExample();
  }
}

In this example, we create a JPanel and add three JRadioButton components, each with a different label. We then create a ButtonGroup and add the three JRadioButton components to the group using the add() method. This ensures that only one JRadioButton in the group can be selected at any given time.

We add the JPanel to the JFrame using the add() method, and then call the pack() method to resize the JFrame to fit its contents, center it on the screen using setLocationRelativeTo(), make it visible with setVisible(true), and set the default close operation to exit the application when the JFrame is closed.

To get the selected JRadioButton, you can use the isSelected() method on each JRadioButton. For example, to get the selected JRadioButton in the above example, you can use the following code:

if (radioButton1.isSelected()) {
    // Option 1 is selected
} else if (radioButton2.isSelected()) {
    // Option 2 is selected
} else if (radioButton3.isSelected()) {
    // Option 3 is selected
} else {
    // No option is selected
}

This code checks which JRadioButton is selected by calling the isSelected() method on each one, and performs an action based on the selected JRadioButton. If no JRadioButton is selected, the else block is executed.

That's a basic example of using JRadioButton in Java.