在 SWT/JFace 應用開發中,FontRegistry 是管理字體資源的核心工具類。它提供字體集中註冊、複用、自動釋放機制,避免重複創建 Font 對象導致的資源洩漏與性能開銷。本文詳解其用法並提供完整示例。
FontData 數組定義字體優先級package swt_jface.demo;
import org.eclipse.jface.resource.FontRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class FontRegistryExample {
Display display = new Display();
Shell shell = new Shell(display);
FontRegistry fontRegistry;
public FontRegistryExample() {
init();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void init() {
shell.setLayout(new GridLayout(2, false));
// 1. 創建 FontRegistry,綁定 Display
fontRegistry = new FontRegistry(display);
// 2. 註冊字體:鍵值 + FontData 數組(支持回退)
fontRegistry.put("button-text", new FontData[]{
new FontData("Arial", 9, SWT.BOLD)
});
fontRegistry.put("code", new FontData[]{
new FontData("Courier New", 10, SWT.NORMAL)
});
// 3. 使用字體
Text text = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP);
text.setFont(fontRegistry.get("code")); // 獲取字體實例
text.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
text.setText("public static void main() {\n\tSystem.out.println(\"Hello\");\n}");
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 2;
text.setLayoutData(gd);
Button executeButton = new Button(shell, SWT.PUSH);
executeButton.setText("Execute");
executeButton.setFont(fontRegistry.get("button-text"));
Button cancelButton = new Button(shell, SWT.PUSH);
cancelButton.setText("Cancel");
cancelButton.setFont(fontRegistry.get("button-text"));
}
public static void main(String[] args) {
new FontRegistryExample();
}
}
// 系統會按順序嘗試,找到第一個可用字體
new FontData[] {
new FontData("PingFang SC", 12, SWT.NORMAL), // macOS 首選
new FontData("Microsoft YaHei", 12, SWT.NORMAL), // Windows 首選
new FontData("Sans", 12, SWT.NORMAL) // Linux/兜底
}
SWT.NORMAL:常規SWT.BOLD:粗體SWT.ITALIC:斜體SWT.BOLD | SWT.ITALICheader-font、code-font、button-fontJFaceResources.getFontRegistry() 獲取全局單例FontRegistry 是 SWT/JFace 資源管理的基石組件,善用它能讓桌面應用的字體管理更優雅、高效、穩定。