Here's one way to generate radio buttons dynamically in Java:
Here is some sample code that demonstrates this process:
import javax.swing.*;
import java.awt.*;
public class RadioButtonExample {
public static void main(String[] args) {
// Create a JFrame to hold the radio buttons
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
Container contentPane = frame.getContentPane();
// Create a JPanel to hold the radio buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1)); // Vertical layout
// Create an array of radio button options
String[] options = {"Option 1", "Option 2", "Option 3"};
// Loop through the options and create a JRadioButton for each one
for (String option : options) {
JRadioButton radioButton = new JRadioButton(option);
buttonPanel.add(radioButton);
}
// Set the first radio button as selected
JRadioButton firstButton = (JRadioButton) buttonPanel.getComponent(0);
firstButton.setSelected(true);
// Add the panel of radio buttons to the main content pane
contentPane.add(buttonPanel, BorderLayout.CENTER);
// Show the frame
frame.setVisible(true);
}
}
This code creates a JFrame that contains a single panel of radio buttons with three options ("Option 1", "Option 2", "Option 3"). It loops through the options array and creates a JRadioButton for each one, which is then added to the buttonPanel using the add() method. It then sets the first radio button as selected using the setSelected() method. Finally, the buttonPanel is added to the main content pane of the frame, and the frame is set visible to display the radio buttons.
Asked: 2021-12-22 11:00:00 +0000
Seen: 8 times
Last updated: Jul 05 '21