我是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);
}
}
答案 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}}会... ...只是说......