首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

SWT/JFace 進階控件:StyledText 富文本編輯器完整指南

     編輯:Java 相關知識

前言

org.eclipse.swt.custom.StyledText 是 SWT 提供的強大富文本編輯控件,支持多樣式、多字體、顏色、背景、行高亮、關鍵字高亮搜索等功能,遠超普通 Text 控件。本文通過 6 個完整示例,系統講解其核心用法。

一、基礎對比:Text 換行與滾動模式

普通 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 動態渲染

通過 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();
}

八、核心 API 速查表

功能關鍵類/方法說明
設置局部樣式setStyleRange(StyleRange) / setStyleRanges(StyleRange[])精確控制字符級樣式
設置整行背景setLineBackground(line, count, Color)高效實現行高亮
動態行樣式LineStyleListener.lineGetStyle(LineStyleEvent)繪製時動態計算,不修改模型
行背景監聽LineBackgroundListener.lineGetBackground(LineBackgroundEvent)簡單行背景設置
獲取樣式範圍getStyleRanges()返回所有 StyleRange 數組
文本操作insert(), replaceTextRange(), getSelectionText()支持帶樣式的文本編輯

九、最佳實踐建議

  • 大文檔場景優先使用 LineStyleListener 而非預先設置海量 StyleRange,避免內存壓力。
  • 搜索高亮時,redraw() 觸發重繪,配合緩存關鍵字位置提升性能。
  • 字體設置建議在創建後統一調用 setFont(),避免混用導致渲染異常。
  • 結合 UndoManager 實現撤銷/重做功能。
  • 導出 RTF/HTML 可參考 TextTransfer 或第三方庫。

StyledText 是構建代碼編輯器、日誌查看器、富文本編輯器的基石,掌握其動態渲染機制是開發高性能文本組件的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved