我是 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/