我試圖向我的GUI添加標籤,按鈕等,但程序只顯示添加到窗口的最後一個項目。我不明白他們爲什麼不一個接一個。它幾乎看起來像我把它們放在彼此之上。附件是我的代碼。只能在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();
}
}
您需要設置[佈局](https://開頭的文檔。 oracle.com/javase/tutorial/uiswing/layout/visual.html)螞蟻跟隨。 BoxLayout或FlowLayout可能是您的最佳選擇。 –
如果你想手動定位項目(單調乏味,但IMO有時需要),你可以做一個setLayout(null);在你的構造函數中,然後爲你添加的每個組件設置邊界。 – JJF
這就是我所認爲的問題。我正在閱讀本參考書,它表明流佈局是默認設置。所以我認爲如果你沒有使用佈局,那麼默認就會取代它。謝謝! – NStafford