作者 主題: 如何在BorderLayout的內容面板中加入GridLayout?  (閱讀 9132 次)

0 會員 與 1 訪客 正在閱讀本文。

NARs

  • 活潑的大學生
  • ***
  • 文章數: 227
    • 檢視個人資料
各位高手~
下面設定了BorderLayout,但是我想在BorderLayout的North面板的位置加入GridLayout,但是下面的程式碼執行後,卻沒有出現任何按鈕,請問是那裡錯了嗎???

代碼: [選擇]
public class layerout extends JFrame {

layerout() {
JPanel toppanel = new JPanel(new BorderLayout()) {
@Override
public String toString() {
return "top";
}
};
Container cp = getContentPane(); //取得內容面版

cp.setLayout(new GridLayout(3, 4, 10, 10));
//指定版面運用3列4行的格狀佈局管理員, 水平與垂直間距分別為10

for(int i=1; i<=7; i++)
cp.add(new JButton("Button_" + i));
//將7個按鈕元件加入版面

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setVisible(true);
JLabel ReceiverLabel=new JLabel("label1");
toppanel.add(ReceiverLabel,BorderLayout.CENTER);
toppanel.add(cp,BorderLayout.North);
toppanel.setPreferredSize(new Dimension(400, 400));
}

public static void main(String args[]) {
new layerout();
}
}
« 上次編輯: 2009-09-07 14:31 由 pinky »

qrtt1

  • 懷疑的國中生
  • **
  • 文章數: 73
    • 檢視個人資料
1. Container(變數cp) 是 JFrame 上的一層透明的容器,你設定它為 GridLayout。這個容易是 JFrame 這類 Top Window 上的東西,不該被加到其他 Container 內,把下面這行取消,至少你的 JButton 會出現。
代碼: [選擇]
toppanel.add(cp, BorderLayout.NORTH);

2. 你建了一個 JPanel 並使用 BorderLayout。
代碼: [選擇]
JLabel ReceiverLabel = new JLabel("label1");
toppanel.add(ReceiverLabel, BorderLayout.CENTER);
// toppanel.add(cp, BorderLayout.NORTH);
toppanel.setPreferredSize(new Dimension(400, 400));

這個 JPanel 應該被加在 cp 內才對。而這樣就跟你想的效果不同。你應該把 JFrame.getContentPane() 設成 BorderLayout。把 JPanel 設成 GridLayout 把  JButton 加進去。把 JPanel 加至 cp 的 NORTH