很可能有許多方法可以做到這一點,但...
你需要去的StyleDocument
參考正在備份的JTextPane
,在給定的字符位置開始,你需要檢查字符給定顏色的屬性,如果true
繼續到文本字符,否則你完成。
import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Srap {
public static void main(String[] args) {
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("I'm a Style", null);
StyleConstants.setForeground(style, Color.red);
try {
doc.insertString(doc.getLength(), "BLAH ", style);
} catch (BadLocationException ex) {
}
StyleConstants.setForeground(style, Color.blue);
try {
doc.insertString(doc.getLength(), "BLEH", style);
} catch (BadLocationException e) {
}
Color color = null;
int startIndex = 0;
do {
Element element = doc.getCharacterElement(startIndex);
color = doc.getForeground(element.getAttributes());
startIndex++;
} while (!color.equals(Color.RED));
startIndex--;
if (startIndex >= 0) {
int endIndex = startIndex;
do {
Element element = doc.getCharacterElement(endIndex);
color = doc.getForeground(element.getAttributes());
endIndex++;
} while (color.equals(Color.RED));
endIndex--;
if (endIndex > startIndex) {
try {
String text = doc.getText(startIndex, endIndex);
System.out.println("Red text = " + text);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
} else {
System.out.println("Not Found");
}
} else {
System.out.println("Not Found");
}
}
}
這個例子簡單認定爲紅色的第一部作品,但是你可以很容易地遍歷整個文檔,並找到所有你想要的話......
嗯,我知道我可以沒有知道我是否可以對待這種類似html,但我想它遵循一般模式 – 2013-04-10 04:30:55
它不是HTML。這是屬性信息如何存儲在JTextPane的'StyledDocument'中。這就是它適用於所有StyledDocuments的原因,包括HTML文檔 – MadProgrammer 2013-04-10 04:31:46