在学习到java的Swing程序设计写一个多选按钮时,发现如下代码写完后,swing页面无法显示组件,必须调节下页面大小才可以显示。
public class JRadioButtonTest extends JFrame{
private static final long serialVersionUID = 1L;
public JRadioButtonTest() {
Container c = getContentPane();
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
JLabel jl = new JLabel("性别");
jl.setFont(new Font("微软雅黑",Font.PLAIN,20));
c.add(jl);
JRadioButton JRB = new JRadioButton("男");
JRB.setFont(new Font("微软雅黑",Font.PLAIN,20));
c.add(JRB);
JRadioButton JRB1 = new JRadioButton("女");
JRB1.setFont(new Font("微软雅黑",Font.PLAIN,20));
c.add(JRB1);
ButtonGroup group = new ButtonGroup();
group.add(JRB);
group.add(JRB1);
setVisible(true);
}
public static void main(String[] args) {
new JRadioButtonTest();
}
}
效果如图:
于是又用了另一种方式来写,如下
public class JRadioButtonTest extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public JRadioButtonTest() {
setBounds(100,100,300,200);
contentPane = new JPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.setBorder(new EmptyBorder(5,5,5,5));
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
JLabel jl = new JLabel("性别");
jl.setFont(new Font("微软雅黑",Font.PLAIN,20));
contentPane.add(jl);
JRadioButton JRB = new JRadioButton("男");
JRB.setFont(new Font("微软雅黑",Font.PLAIN,20));
contentPane.add(JRB);
JRadioButton JRB1 = new JRadioButton("女");
JRB1.setFont(new Font("微软雅黑",Font.PLAIN,20));
contentPane.add(JRB1);
ButtonGroup group = new ButtonGroup();
group.add(JRB);
group.add(JRB1);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
JRadioButtonTest frame = new JRadioButtonTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
改成这种方式后,可以正常显示了,不需要拖动窗口,运行程序即可显示组件。如图
通过比较与观察,得出结论是与setVisible的位置有关,这个方法是设置页面可见的,如果把它放在组件对象的前面,那么刚打开页面就无法显示组件。由于在写Swing程序时,习惯性的把页面必须的设置写完,就没注意到这点。
得出结论
这个问题的结论就是:setVisible必须放在最后,这样才可以把所有设置可以显示的组件在刚打开页面时,就显示出来。