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

标签 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);
    }

}

最佳答案

第一个问题是为什么?为什么要将单选按钮添加到 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 等扩展,然后将其添加到 main 中的 JFrame

已更新

我刚刚做了一些测试,这样做(向标签添加按钮)效果不佳,因为 JLabel 根据文本和图标计算其首选尺寸,而不是其内容(例如像 JPanel 之类的东西)...只是说...

关于java - java GUI 的问题。我无法在 JLabel 中显示 JRadioButtons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23074580/

相关文章:

java - JTable 单元格编辑器数字格式

ruby-on-rails - 从局部添加内容到布局

java - JAVA 中的 GridBagLayout

java - 找到第一个匹配的条目并将匹配的条目值分配给变量

java - 在 Android 中将嵌套的 Class<MyInterface<T>> 作为参数传递

java - 从数组到 JPanel 的绘制点

html - 如何在div中垂直居中文本?

java - 生成随机数量的字符

java - 使用 Gson 反序列化对象和列表

java - 使用 Java 中的 Swing 进行文件处理编程