ColorPane – 可以抓住不同角色的字符串?

我目前正在处理一个给我的旧项目,它目前使用java swing并且有一个基本的gui。 它有一个ColorPane,它扩展了Jtextpane以更改所选文本的颜色。

它使用这种方法

public void changeSelectedColor(Color c) { changeTextAtPosition(c, this.getSelectionStart(), this.getSelectionEnd()); } 

假设string =“Hello World!” 你好颜色是绿色世界是黑色的。 我如何从Jtextpane中获取基于其颜色的Hello out。 我尝试了一种笨重的方式,只是存储所选择的单词,因为我改变了颜色,但有没有办法可以一次抓住所有绿色文本? 我试过谷歌搜索但是…它没有真正想出任何好的方法。 谁能指出我正确的方向?

可能有很多方法可以做到这一点,但……

您需要获取对支持JTextPaneStyleDocument的引用,从给定的字符位置开始,您需要检查给定颜色的字符属性,如果为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"); } } } 

这个例子简单地找到了第一个红色的作品,但你可以轻松地走完整个文档并找到你想要的所有单词……