首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java Swing 文本域關鍵字高亮:使用 JTextPane 實現 Word 樣式選中效果

     編輯:程式設計綜合問答

需求

在文本域中搜尋關鍵字,並將所有匹配處「高亮選中」(類似 Word 的「尋找」功能),而非僅靜態顯示。

JTextArea 無法實現的原因

`JTextArea` 只支援純文本,**不支援局部樣式(顏色、字體、背景)**,無法實現「部分文字高亮」。

解決方案:改用 JTextPane + StyledDocument

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

// 定義高亮樣式
Style highlight = textPane.addStyle("Highlight", null);
StyleConstants.setBackground(highlight, Color.YELLOW);
StyleConstants.setBold(highlight, true);

// 高亮關鍵字方法
public void highlightKeyword(String keyword) {
    String content = textPane.getText();
    int pos = 0;
    while ((pos = content.indexOf(keyword, pos)) >= 0) {
        doc.setCharacterAttributes(pos, keyword.length(), highlight, false);
        pos += keyword.length();
    }
}

// 清除高亮
public void clearHighlight() {
    Style normal = textPane.getStyle("Normal");
    doc.setCharacterAttributes(0, doc.getLength(), normal, true);
}

進階:即時搜尋高亮

  • 在 `DocumentListener` 中觸發高亮更新(需注意效能,大文本用延遲或背景執行緒)。
  • 使用 `Highlighter` 介面(`DefaultHighlighter`)可實現非侵入式高亮,不改變文檔屬性,適合臨時搜尋。

核心結論:必須使用 `JTextPane` 或 `JEditorPane` 等支援富文本的組件,`JTextArea` 做不到。

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