BorderLayout 是 AWT 五大預設佈局管理器之一,將容器劃分為北、南、東、西、中五個區域。本例展示如何使用巢狀面板(Nested Panels)結合 BorderLayout 與 FlowLayout 建構複雜介面。
import java.awt.*;
import java.applet.*;
public class NestedPanels extends Applet {
protected Choice choice;
protected Button b;
protected Label messageBox;
public NestedPanels() {
// 中央面板使用 BorderLayout
Panel center = new Panel();
center.setLayout(new BorderLayout());
center.add(new Button("North"), BorderLayout.NORTH);
center.add(new Button("South"), BorderLayout.SOUTH);
center.add(new Button("West"), BorderLayout.WEST);
center.add(new Button("East"), BorderLayout.EAST);
center.add(new Button("Center"), BorderLayout.CENTER);
// 底部面板使用 FlowLayout
Panel south = new Panel();
south.setLayout(new FlowLayout());
b = new Button("Help");
south.add(b);
choice = new Choice();
choice.addItem("one");
choice.addItem("two");
choice.addItem("three");
choice.addItem("four");
choice.addItem("five");
south.add(choice);
messageBox = new Label("This is a message bar.");
south.add(messageBox);
// 整體 Applet 使用 BorderLayout
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
add(new Button("West"), BorderLayout.WEST); // 原碼拼寫 WSET,已修正
add(new Button("East"), BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
add(center, BorderLayout.CENTER);
}
}
重點說明:
Panel 再加入該區域。BorderLayout,底部面板用 FlowLayout。BorderLayout.WSET,正確為 BorderLayout.WEST。現代 Swing 開發建議改用 JPanel 並搭配 BorderLayout,用法相同。