Synth 是 JDK 5 引入的可換膚觀感架構,透過 XML 定義元件外觀(圖片、顏色、字型、邊距),完全分離「外觀」與「邏輯」,無需寫繪圖代碼即可實現豐富 UI。
src/
com/example/
MainFrame.java
resources/
synth/
demo.xml
images/
btn_normal.png
btn_hover.png
btn_pressed.png
<?xml version="1.0" encoding="UTF-8"?>
<synth>
<style id="buttonStyle">
<!-- 預設狀態 -->
<state>
<imagePainter method="buttonBackground"
path="images/btn_normal.png"
sourceInsets="9 10 9 12" paintCenter="true" stretch="true"/>
<insets top="9" left="10" bottom="9" right="12"/>
<font name="微軟正黑體" size="16"/>
<color type="TEXT_FOREGROUND" value="#FFFFFF"/>
</state>
<!-- 滑鼠懸停 -->
<state value="MOUSE_OVER">
<imagePainter method="buttonBackground" path="images/btn_hover.png"
sourceInsets="9 10 9 12" paintCenter="true" stretch="true"/>
<insets top="9" left="10" bottom="9" right="12"/>
<color type="TEXT_FOREGROUND" value="#FFFF00"/>
</state>
<!-- 按下 -->
<state value="PRESSED">
<imagePainter method="buttonBackground" path="images/btn_pressed.png"
sourceInsets="10 12 8 9" paintCenter="true" stretch="true"/>
<insets top="10" left="12" bottom="8" right="9"/>
<color type="TEXT_FOREGROUND" value="#00FF00"/>
</state>
<property key="Button.margin" type="insets" value="0 0 0 0"/>
</style>
<bind style="buttonStyle" type="region" key="Button"/>
</synth>
| 屬性 | 說明 | |
|---|---|---|
method | 繪製方法:buttonBackground、textBackground、sliderTrack 等 | |
sourceInsets | 九宮格切圖邊距:上 右 下左,保護邊角不拉伸變形 | |
paintCenter | true=中心區域也繪製,false=僅繪製邊框 | |
stretch | true=拉伸填充,false=平鋪重複 | |
state value | ENABLED、MOUSE_OVER、PRESSED、DISABLED、FOCUSED、SELECTED |
| 現象 | 原因 | 解決 |
|---|---|---|
| 圖片不顯示 | 路徑錯誤、大小寫、未打包進 JAR | 用 getClass().getResource() 驗證路徑,確認 resources 目錄被編譯輸出 |
| 邊框變形 | sourceInsets 設定不當 | 按九宮格原理:邊框寬度 = 圖片邊緣不可拉伸區域 |
| 字體無效 | 系統無該字體 | 用邏輯字體名或載入 .ttf:Font.createFont(Font.TRUETYPE_FONT, is) |
Synth 讓 Swing 擁有「CSS 風格」的外觀定義能力,掌握 XML + 九宮格圖片,即可零代碼打造專業級桌面應用介面。