org.eclipse.swt.custom.StyledText 是 SWT 提供的強大富文本編輯控件,支持多樣式、多字體、顏色、背景、行高亮、關鍵字高亮搜索等功能,遠超普通 Text 控件。本文通過 6 個完整示例,系統講解其核心用法。
普通 Text 控件通過 SWT.WRAP 實現自動換行,SWT.MULTI 支持多行。
// WrapLines.java
Text text1 = new Text(shell, SWT.BORDER | SWT.MULTI); // 不換行,需水平滾動
Text text2 = new Text(shell, SWT.BORDER | SWT.WRAP); // 自動換行
text1.setText(line); text2.setText(line);
VerifyListener 可在輸入前攔截字符(如實現 Ctrl+V 粘貼轉換),ModifyListener 監聽內容變化。
// RemarksText.java
text.addVerifyListener(e -> {
if (e.character == ' ' && (e.stateMask & SWT.CTRL) != 0) {
if (text.getText(e.start-1, e.start-1).equals("V")) e.text = "erifyListener";
else e.doit = false;
}
});
text.addModifyListener(e -> System.out.println("字符數: " + text.getCharCount()));
// UserPassword.java
Text textPassword = new Text(shell, SWT.SINGLE | SWT.BORDER);
textPassword.setEchoChar('*'); // 設置回顯字符
通過 LineBackgroundListener 實現類似編輯器的行高亮效果。
// HighlightOddLine.java
styledText.addLineBackgroundListener(event -> {
if (styledText.getLineAtOffset(event.lineOffset) % 2 == 1)
event.lineBackground = display.getSystemColor(SWT.COLOR_YELLOW);
});
styledText.setText("Line 0\r\nLine 1\r\nLine 2\r\nLine 3\r\nLine 4\r\nLine 5\r\nLine 6");
StyleRange 定義文本區段樣式,setStyleRange、setStyleRanges 應用樣式,setLineBackground 設置整行背景。
// SetLineBackground.java
StyleRange style = new StyleRange();
style.start = 2; style.length = 3;
style.foreground = display.getSystemColor(SWT.COLOR_BLUE);
style.background = display.getSystemColor(SWT.COLOR_YELLOW);
style.fontStyle = SWT.BOLD;
styledText.setStyleRange(style);
styledText.setLineBackground(0, 1, display.getSystemColor(SWT.COLOR_GREEN));
styledText.setLineBackground(1, 1, display.getSystemColor(SWT.COLOR_YELLOW));
通過 LineStyleListener 在繪製每行時動態計算高亮樣式,實現實時搜索高亮,不修改文檔內容。
// SearchStyleText.java
styledText.addLineStyleListener(event -> {
if (keyword == null || keyword.isEmpty()) { event.styles = new StyleRange[0]; return; }
String line = event.lineText;
List styles = new ArrayList<>();
int idx = -1;
while ((idx = line.indexOf(keyword, idx + 1)) >= 0) {
styles.add(new StyleRange(event.lineOffset + idx, keyword.length(),
null, display.getSystemColor(SWT.COLOR_YELLOW), SWT.NORMAL));
}
event.styles = styles.toArray(new StyleRange[0]);
});
// 搜索按鈕觸發重繪
button.addSelectionListener(e -> {
keyword = keywordText.getText();
styledText.redraw(); // 觸發 LineStyleListener
});
// SampleStyledText.java
StyleRange[] ranges = styledText.getStyleRanges(); // 獲取所有樣式範圍
// 打印調試工具方法
private String printStyleRanges(StyleRange[] ranges) {
if (ranges == null) return "null";
StringBuilder sb = new StringBuilder();
for (StyleRange r : ranges) sb.append(r).append("\n");
return sb.toString();
}
| 功能 | 關鍵類/方法 | 說明 |
|---|---|---|
| 設置局部樣式 | setStyleRange(StyleRange) / setStyleRanges(StyleRange[]) | 精確控制字符級樣式 |
| 設置整行背景 | setLineBackground(line, count, Color) | 高效實現行高亮 |
| 動態行樣式 | LineStyleListener.lineGetStyle(LineStyleEvent) | 繪製時動態計算,不修改模型 |
| 行背景監聽 | LineBackgroundListener.lineGetBackground(LineBackgroundEvent) | 簡單行背景設置 |
| 獲取樣式範圍 | getStyleRanges() | 返回所有 StyleRange 數組 |
| 文本操作 | insert(), replaceTextRange(), getSelectionText() | 支持帶樣式的文本編輯 |
LineStyleListener 而非預先設置海量 StyleRange,避免內存壓力。redraw() 觸發重繪,配合緩存關鍵字位置提升性能。setFont(),避免混用導致渲染異常。UndoManager 實現撤銷/重做功能。TextTransfer 或第三方庫。StyledText 是構建代碼編輯器、日誌查看器、富文本編輯器的基石,掌握其動態渲染機制是開發高性能文本組件的關鍵。