三檔案架構
- 繪圖元件 (
NotHelloWorldComponent.java):繼承 JComponent,覆寫 paintComponent(Graphics g)。
- 視窗框架 (
NotHelloWorldFrame.java):繼承 JFrame,加入元件並 pack() 自適應大小。
- 啟動類 (
NotHelloWorld.java):在事件派發執行緒 (EDT) 中建立視窗。
核心代碼
1. 繪圖元件
public class NotHelloWorldComponent extends JComponent {
public static final int MESSAGE_X = 75, MESSAGE_Y = 75;
private static final int DEFAULT_WIDTH = 300, DEFAULT_HEIGHT = 300;
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g; // 2D 繪圖上下文
Rectangle2D rect = new Rectangle2D.Double(50, 50, 200, 150);
g2.drawString("Not a hello, World program", MESSAGE_X, MESSAGE_Y);
g2.draw(rect);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
2. 視窗框架
public class NotHelloWorldFrame extends JFrame {
public NotHelloWorldFrame() {
add(new NotHelloWorldComponent());
pack(); // 依據元件首選大小調整視窗
}
}
3. 啟動類 (關鍵:EDT)
public class NotHelloWorld {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new NotHelloWorldFrame();
frame.setTitle("NotHelloWorldFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
關鍵概念說明
- EDT (Event Dispatch Thread):Swing 所有 UI 操作必須在 EDT 執行,
EventQueue.invokeLater 確保此點。
paintComponent:繪圖回調,**不要**直接呼叫,由系統觸發;傳入 Graphics 物件。
Graphics2D:提供幾何圖形、文字、渲染提示等進階繪圖功能。
pack():根據子元件 getPreferredSize() 自動計算視窗大小。
擴充方向
- 滑鼠/鍵盤事件監聽 (
MouseListener, KeyListener)
- 動畫循環 (
Timer 定時 repaint())
- 雙重緩衝 (
RepaintManager 預設開啟)