java GUI问题。我无法在JLabel中显示JRadioButtons

时间:2014-04-15 04:18:29

标签: java swing layout jlabel jradiobutton

我是Java新手;但是我爆炸了。我觉得我错过了一些非常简单的事情;但我无法弄清楚。

我希望RadioButtons显示在JFrame中。"

public class HelloWorldFrame extends JFrame
{
    private TitledBorder title;

    public HelloWorldFrame()
    {
        super("Hello World!                  ");
        JFrame helloWorld = new JFrame();
        JLabel label = new JLabel();
        title = BorderFactory.createTitledBorder("Language");
        title.setTitleJustification(TitledBorder.LEFT);
        label.setBorder(title);
        add(label);

        setSize(300, 200);

        JRadioButton button1 = new JRadioButton("English");
        JRadioButton button2 = new JRadioButton("French");
        JRadioButton button3 = new JRadioButton("Spanish");
        ButtonGroup bG = new ButtonGroup();
        bG.add(button1);
        bG.add(button2);
        bG.add(button3);
        label.add(button1);
        label.add(button2);
        label.add(button3);
        helloWorld.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}


//The main class starts here

public class HelloWorldApp
{
    public static void main(String[] args)
    {
        JFrame helloWorld = new HelloWorldFrame();
        helloWorld.setVisible(true);
    }

}

1 个答案:

答案 0 :(得分:3)

第一个问题是为什么?为什么要将单选按钮添加到JLabel

话虽如此,你可以将标签布局管理器设置为其他的默认值null ...

label.setLayout(new FlowLayout());
label.add(button1);
label.add(button2);
label.add(button3);

接下来......您的课程从JFrame延伸,但在您的构造函数中,您正在创建另一个JFrame,这意味着当您这样做时...

JFrame helloWorld = new HelloWorldFrame();
helloWorld.setVisible(true);

不会显示任何内容,因为框架中没有添加任何内容。

相反,让您的课程从JFrame扩展,然后将其添加到JFrame

中的main

<强>更新

我刚做了一些测试并且这样做(向标签添加按钮)不会很好,因为JLabel根据文本和图标计算它的首选大小,而不是它的内容(如{ {1}}会... ...只是说......