下面的代码:
public class PnlMenuRadioButtons extends JPanel {
public PnlMenuRadioButtons(String menuName) {
super();
setLayout(new BorderLayout());
Font radioButtonsFont = new Font("Arial", Font.PLAIN, 14);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new BorderLayout());
titlePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
add(titlePanel, BorderLayout.NORTH);
Font menuTitleFont = new Font("Tempus Sans ITC", Font.BOLD, 16);
JLabel lblMenu = new JLabel(menuName);
lblMenu.setFont(menuTitleFont);
titlePanel.add(lblMenu, BorderLayout.WEST);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
add(contentPanel, BorderLayout.CENTER);
/*
//VERSION 1
//FROM HERE
ButtonGroup btngrp = new ButtonGroup();
JRadioButton rdbtn = new JRadioButton("hi");
btngrp.add(rdbtn);
contentPanel.add(rdbtn);
JRadioButton rdbtn2 = new JRadioButton("hello");
btngrp.add(rdbtn2);
contentPanel.add(rdbtn2);
//TO HERE
*/
//VERSION 2
//FROM HERE
String[] strs = {"hi", "hello"};
ButtonGroup radioButtonsGroup = new ButtonGroup();
for(int i = 0; i < 2; i++) {
JRadioButton rdbtn = new JRadioButton((String)Array.get(strs, i));
rdbtn.setFont(radioButtonsFont);
radioButtonsGroup.add(rdbtn);
contentPanel.add(rdbtn);
}
//TO HERE
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
add(buttonPanel, BorderLayout.SOUTH);
Font buttonFont = new Font("Arial", Font.PLAIN, 14);
JButton btnBack = new JButton("Back");
btnBack.setFont(buttonFont);
btnBack.setActionCommand("Back");
buttonPanel.add(btnBack);
JButton btnGO = new JButton("Go");
btnGO.setFont(buttonFont);
btnGO.setActionCommand("Go");
buttonPanel.add(btnGO);
}
}
如果我使用版本1,contentPanel
会正确添加JRadioButton
。
但是我想要一个循环,因为我想用用户选择的JRadioButton
的数量来改变代码,所以它将是随机的。
但是如果我使用版本2,似乎contentPanel
从来没有添加JRadioButton
。我错过了什么?
谢谢。
1条答案
按热度按时间2ic8powd1#
您的代码末尾缺少一个}。请尝试为contentPanel添加不同的变量名。add(),可能是这样。