当我运行下面的代码时,前两个按钮不会出现;但是,第三个在框架中可见。
public class RadioButton {
RadioButton(){
JFrame frame = new JFrame();
JRadioButton button1 = new JRadioButton("One");
button1.setBounds(50, 20, 50, 20);
JRadioButton button2 = new JRadioButton("Two");
button2.setBounds(50, 50, 50, 20);
JRadioButton button3 = new JRadioButton("Three");
button2.setBounds(50, 80, 50, 20);
ButtonGroup bg = new ButtonGroup();
bg.add(button1);
bg.add(button2);
bg.add(button3);
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new RadioButton();
}
}
最佳答案
我想既然OP将布局管理器设置为空,绝对定位就是我们想要的。通常不建议这样做。请参阅tutorial .
您需要按如下方式重新排序代码 - 即在设置组件边界之前设置布局。
public class RadioButton {
RadioButton() {
JFrame frame = new JFrame();
JRadioButton button1 = new JRadioButton("One");
JRadioButton button2 = new JRadioButton("Two");
JRadioButton button3 = new JRadioButton("Three");
ButtonGroup bg = new ButtonGroup();
frame.setLayout(null);
bg.add(button1);
bg.add(button2);
bg.add(button3);
frame.setSize(300, 300);
frame.add(button1);
frame.add(button2);
frame.add(button3);
button1.setBounds(50, 20, 80, 20);
button2.setBounds(50, 50, 80, 20);
button3.setBounds(50, 80, 80, 20);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new RadioButton();
}
}
我使用的是 OS X,我需要将按钮弄大一点以避免其标题显示为“...”。最后我使用了 invokeLater
,IIRC 是最佳实践。
关于java - 程序未返回 RadioButton 的正确结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22796676/