背景:可訪問性需求
弱視用戶需要高對比度、大字體、大圖標。J2SE 1.4.2 新增 Windows XP/GTK+ L&F,但 Metal 跨平台、可簽名 Applet 使用、定制靈活性高,仍具不可替代價值。
Metal L&F 定制兩大核心
1. 主題機制控制顏色與字體
- `MetalLookAndFeel` 委托 `MetalTheme` 提供顏色/字體值。
- 繼承 `DefaultMetalTheme`,重寫 8 色 (`getPrimary1-3`、`getSecondary1-3`、`getBlack/White`) 與 6 字體 (`getControlTextFont` 等) 方法。
- 避免硬編碼:讀取外部屬性文件 (`HighContrastLAF.properties`) 動態返回值,支持運行時切換主題。
2. 圖標縮放解決大字體配小圖標問題
- Metal 使用 `MetalIconFactory` 動態繪製矢量圖標,多數無尺寸參數。
- 方案:實現 `Icon` 包裝類 `MagnifiedIcon`,構造時傳入原圖標與縮放因子,`paintIcon` 中用 `Graphics2D.scale()` 繪製放大版(位圖格式,質量略損但可接受)。
- 重寫 `initComponentDefaults(UIDefaults)`,遍歷標準圖標鍵 (如 `CheckBox.icon`、`Tree.openIcon` 等),替換為 `MagnifiedIcon` 實例。
外部配置文件示例
# 白底黑字大字體高對比度
name = High Contrast Look And Feel
iconMagnificationFactor = 2.5
fontName = Dialog
fontSize = 30
backgroundColor = FFFFFF
foregroundColor = 000000
primaryColor1 = 000000
...
selectionBackground = 000000
selectionForeground = FFFFFF
啟用方式
主方法最前調用 `UIManager.setLookAndFeel("HighContrastLAF")`,或通過系統屬性 `java -DplafName=HighContrastLAF` 動態指定。
效果展示
截圖對比:默認主題 vs 高對比度大字體主題 vs 黑底白字主題,圖標與字體完美協調,滿足可訪問性標準。