在文本域中搜尋關鍵字,並將所有匹配處「高亮選中」(類似 Word 的「尋找」功能),而非僅靜態顯示。
`JTextArea` 只支援純文本,**不支援局部樣式(顏色、字體、背景)**,無法實現「部分文字高亮」。
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);
}
核心結論:必須使用 `JTextPane` 或 `JEditorPane` 等支援富文本的組件,`JTextArea` 做不到。