AWT(Abstract Window Toolkit)是 Java 早期的 GUI 工具包,提供跨平台的窗口、組件、事件處理與布局管理。本文系統講解 Frame、Panel 核心容器及 FlowLayout、BorderLayout、GridLayout 三大布局管理器,並以計算器界面為綜合實例。
Window, Panel, ScrollPane。Frame -> Window -> Container -> ComponentsetBounds(x,y,w,h), setTitle(), setBackground(), setVisible(true)Frame frame = new Frame("我的第一個窗口");
frame.setBounds(50, 50, 300, 200);
frame.setBackground(Color.PINK);
frame.setVisible(true);
Panel -> Container -> ComponentFrame frame = new Frame("Panel 示例");
frame.setBounds(50, 50, 500, 300);
Panel panel = new Panel();
panel.setBackground(Color.PINK);
frame.add(panel); // 添加到 Frame
frame.setVisible(true);
new FlowLayout(align, hgap, vgap),align:LEFT, CENTER, RIGHT。frame.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 40));
NORTH, SOUTH, EAST, WEST, CENTER,每區域僅一組件。frame.add(btn, BorderLayout.NORTH)。new GridLayout(rows, cols, hgap, vgap)。GridLayout gl = new GridLayout(3, 2, 5, 5); // 3行2列 frame.setLayout(gl);
public class CalculatorDemo {
public static void main(String[] args) {
Frame frame = new Frame("計算器");
frame.setBounds(100, 100, 300, 420);
// Frame 默認 BorderLayout
// 北部:顯示框
TextField tf = new TextField();
frame.add(tf, BorderLayout.NORTH);
// 中部:按鈕面板,使用 GridLayout
Panel panel = new Panel();
panel.setLayout(new GridLayout(4, 4, 1, 1));
frame.add(panel, BorderLayout.CENTER);
String[] keys = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", ".", "=", "/"
};
for (String key : keys) {
panel.add(new Button(key));
}
frame.setVisible(true);
}
}
setLayout(null))需手動調用 setBounds(),會導致平台相關性,不推薦。AWT 雖已非主流,但其「容器-布局-組件」核心模型被 Swing、JavaFX 繼承,掌握 AWT 基礎有助於深度理解 Java GUI 架構演進。