[英]Java - Can't see JRadioButtons
I am a beginner and I was practicing JRadioButtons. 我是一个初学者,正在练习JRadioButtons。 I realised that I can't see my JRadioButtons if I'll not set my layout as 'FlowLayout()'
. 我意识到如果不将布局设置为'FlowLayout()'
, 就看不到我的JRadioButtons 。 I want to set the location of the buttons by myself. 我想自己设置按钮的位置。
I posted my code below, can anyone help me what am I doing wrong ? 我在下面发布了我的代码,有人可以帮我做错什么吗?
Thanks! 谢谢!
private JFrame frame;
private JPanel panel;
private JRadioButton btn1, btn2;
public JBButtons() {
form();
radioButtons();
frame.add(panel);
frame.setVisible(true);
}
public void form(){
frame = new JFrame("Frame");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
//panel.setLayout(new FlowLayout());
}
public void radioButtons() {
ButtonGroup group = new ButtonGroup();
btn1 = new JRadioButton("btn1");
btn1.setSelected(true);
btn1.setLocation(50, 50);
btn2 = new JRadioButton("btn2");
btn2.setLocation(50, 70);
group.add(btn1);
group.add(btn2);
panel.add(btn1);
panel.add(btn2);
}
public static void main(String[] args) {
new JBButtons();
}
The issue with absolute positioning or null layout is - it requires you to set the sizes of all your components, otherwise they will stay their default zero-size and won't show up. 绝对定位或空布局的问题是-它要求您设置所有组件的尺寸,否则它们将保持其默认的零尺寸且不会显示。 Better use a layout manager - https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html 更好地使用布局管理器-https: //docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Add this part of the code when adding the RadioButton to the panel, use the property .setBounds(x, y, width, heigth)
. 在将RadioButton添加到面板时,请使用.setBounds(x, y, width, heigth)
属性添加这部分代码。
panel.add(btn1);
btn1.setBounds(90, 59, 93, 23);
panel.add(btn2);
btn2.setBounds(180, 60, 93, 23);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.