2004 年初接觸 Java 時,因工作環境與惰性未深入。如今 Java 成為主力工具,用 JBuilder 2005 開發,閱讀《Thinking in Java》經典,逐漸從「被迫使用」轉為「真心熱愛」。本文記錄這一心路歷程與實踐感悟。
痛點:近 20 個組件佈局,手寫 GridBagConstraints 繁瑣易錯、調整位置需大量改代碼。
public class LayoutHelper {
private final Map templates = new HashMap<>();
private final Container container;
private final GridBagLayout layout;
public LayoutHelper(Container container) {
this.container = container;
this.layout = new GridBagLayout();
container.setLayout(layout);
}
// 註冊樣板約束
public void registerTemplate(String name, GridBagConstraints gbc) {
templates.put(name, (GridBagConstraints) gbc.clone());
}
// 一鍵添加組件
public void addComponent(Component comp, String templateName, int gridx, int gridy) {
GridBagConstraints gbc = (GridBagConstraints) templates.get(templateName).clone();
gbc.gridx = gridx;
gbc.gridy = gridy;
layout.setConstraints(comp, gbc);
container.add(comp);
}
// 批量添加:自動換行
public void addRow(Component[] comps, String templateName, int startY) {
for (int i = 0; i < comps.length; i++) {
addComponent(comps[i], templateName, i, startY);
}
}
}
LayoutHelper helper = new LayoutHelper(panel);
helper.registerTemplate("label", new GBC(0,0).anchor(WEST).insets(5));
helper.registerTemplate("field", new GBC(1,0).fill(HORIZONTAL).weightx(1).insets(5));
helper.addComponent(new JLabel("用戶名:"), "label", 0, 0);
helper.addComponent(new JTextField(20), "field", 1, 0);
helper.addComponent(new JLabel("密碼:"), "label", 0, 1);
helper.addComponent(new JPasswordField(20), "field", 1, 1);
// 調整位置只需修改 gridx/gridy,無需動約束代碼
核心思想:樣板化約束 + 參數化位置 + 封裝細節,將佈局代碼從「手工拼裝」升級為「聲明式組裝」。
| 階段 | 心態 | 關注點 | 代碼風格 |
|---|---|---|---|
| 初學 | 抗拒、抱怨冗長 | 語法、API 記憶 | 面向過程、大主類、複製粘貼 |
| 入門 | 接受、嘗試 OOP | 類設計、模式套用 | 機械應用模式、過度設計 |
| 實戰 | 熟練、工具化思維 | 業務建模、可維護性 | 領域驅動、薄控制器、豐富模型 |
| 熱愛 | 享受、持續優化 | 工程效能、團隊協作 | 自動化、規範化、文檔化、可觀測 |
Java 不僅是語言,更是一套成熟的工程哲學體系。當你不再與語言對抗,而是借力語言特性解決業務問題時,熱愛自然生長。