【发布时间】:2016-03-23 22:04:28
【问题描述】:
我正在尝试向我的 GUI 添加标签、按钮等,但程序只显示添加到窗口中的最后一项。我不明白他们为什么不一个接一个地去。几乎好像我把它们放在一起。附上我的代码。
import java.awt.*;
import java.awt.event.*;
public class ZooGUIStafford extends Frame {
//Text fields for animal input
TextField ani1, ani2, ani3, ani4, ani5;
public ZooGUIStafford()
{
//Size of window
this.setTitle("Zoo Database");
this.setSize(400, 400);
this.setVisible(true);
//Welcome label
Label welcome = new Label("Welcome to the Zoo Database!");
this.add(welcome);
Label an1 = new Label("Enter animal type 1: ");
this.add(an1);
addWindowListener(new MyWindowAdapter(this));
}
class MyWindowAdapter extends WindowAdapter{
ZooGUIStafford myWindow = null;
MyWindowAdapter(ZooGUIStafford myWindow)
{
this.myWindow = myWindow;
}
public void windowClosing(WindowEvent e)
{
myWindow.setVisible(false);
}
}
public static void main(String args[])
{
new ZooGUIStafford();
}
}
【问题讨论】:
-
您需要设置layout 以便组件跟随。 BoxLayout 或 FlowLayout 可能是您的最佳选择。
-
如果您想手动定位项目(乏味但有时需要 IMO),您可以执行 setLayout(null);然后在你的构造函数中为你添加的每个组件设置边界。
-
这就是我认为的问题所在。我正在阅读这本参考书,它表明流布局是默认设置。所以我假设如果你不使用布局,那么默认值会取而代之。谢谢!
标签: java user-interface