可能有很多方法可以做到这一点,但是......
您需要获取对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 Scrape {
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");
}
}
}
这个例子简单地找到了第一个红色的单词,但是你可以很容易地遍历整个文档并找到你想要的所有单词......