java - 程序未返回 RadioButton 的正确结果

标签 java swing jradiobutton

当我运行下面的代码时,前两个按钮不会出现;但是,第三个在框架中可见。

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/

相关文章:

java - 基于JRadioButton动态更改JPanel

java - 通过套接字发送图像而不关闭套接字

运行时的 Java 观感

java - 无法将按钮图标与另一个图标进行比较

java - 单击按钮从 jtable 中删除选定的行

Java:如何根据选择的单选按钮更改图像面板中的图像

Java swing,如何调用选项菜单点击上的函数?

java - Spring MVC 应用程序启动时出现奇怪的错误

java - 回文忽略空格和标点符号

java - Java GUI 设计的问题