Sure, here's an example of using JRadioButtons in Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JRadioButtonExample extends JFrame implements ActionListener {
private JRadioButton radioButton1, radioButton2;
private ButtonGroup buttonGroup;
private JLabel label;
public JRadioButtonExample() {
// Set up the frame
setTitle("JRadioButton Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Create the radio buttons and button group
radioButton1 = new JRadioButton("Option 1");
radioButton2 = new JRadioButton("Option 2");
buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
// Add action listeners to the radio buttons
radioButton1.addActionListener(this);
radioButton2.addActionListener(this);
// Create a label to display the selected option
label = new JLabel("No option selected");
// Add the components to the frame
add(radioButton1);
add(radioButton2);
add(label);
// Show the frame
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (radioButton1.isSelected()) {
label.setText("Option 1 selected");
} else if (radioButton2.isSelected()) {
label.setText("Option 2 selected");
}
}
public static void main(String[] args) {
JRadioButtonExample example = new JRadioButtonExample();
}
}
This example creates a JFrame window with two JRadioButtons labeled "Option 1" and "Option 2". The JRadioButtons are added to a ButtonGroup to ensure that only one can be selected at a time. An ActionListener is added to each JRadioButton to handle the selection events.
When a JRadioButton is selected, the actionPerformed method is called and the label text is updated to reflect the selected option. In this example, the label displays either "Option 1 selected" or "Option 2 selected" depending on which button is selected.