Ключ к реализации дизайна, который вы желаете (я думаю), состоит в том, чтобы использовать массивы в полную силу. Например, у вас может быть двухмерный массив String, содержащий тексты JRadioButton, и одномерный массив ButtonGroups, а затем вы сможете легко настроить графический интерфейс и запросить графический интерфейс для циклов и вложенных в циклы используя превосходное предложение mKorbel).
Например:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Foo002 extends JPanel {
public static final String[][] RADIO_TEXTS = {
{"A1","A2","A3","A4"}, {"B1","B2","B3","B4"},
{"C1","C2","C3","C4"}, {"D1","D2","D3","D4"},
{"E1","E2","E3","E4"}, {"F1","F2","F3","F4"},
{"G1","G2","G3","G4"}, {"H1","H2","H3","H4"},
{"I1","I2","I3","I4"}, {"J1","J2","J3","J4"},
{"K1","K2","K3","K4"}, {"L1","L2","L3","L4"},
{"M1","M2","M3","M4"}, {"N1","N2","N3","N4"},
{"O1","O2","O3","O4"}, {"P1","P2","P3","P4"},
{"Q1","Q2","Q3","Q4"}, {"R1","R2","R3","R4"},
{"S1","S2","S3","S4"}, {"T1","T2","T3","T4"}
};
private ButtonGroup[] btnGroups = new ButtonGroup[RADIO_TEXTS.length];
public Foo002() {
JPanel radioPanel = new JPanel(new GridLayout(0, 2));
for (int i = 0; i < RADIO_TEXTS.length; i++) {
JPanel panel = new JPanel(new GridLayout(1, 0));
btnGroups[i] = new ButtonGroup();
for (int j = 0; j < RADIO_TEXTS[i].length; j++) {
String text = RADIO_TEXTS[i][j];
JRadioButton rBtn = new JRadioButton(text);
rBtn.setActionCommand(text);
btnGroups[i].add(rBtn);
panel.add(rBtn);
}
panel.setBorder(BorderFactory.createLineBorder(Color.black));
radioPanel.add(panel);
}
JButton getRadioChoicesBtn = new JButton(new AbstractAction("Get Radio Choices") {
public void actionPerformed(ActionEvent arg0) {
for (ButtonGroup btnGroup : btnGroups) {
ButtonModel btnModel = btnGroup.getSelection();
if (btnModel != null) {
System.out.println("Selected Button: " + btnModel.getActionCommand());
}
}
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(getRadioChoicesBtn);
setLayout(new BorderLayout());
add(radioPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("RadioPanels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Foo002());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}