0

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

它使用这种方法

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

说那个字符串=“Hello World!” 你好颜色是绿色世界是黑色。如何根据 Jtextpane 中的颜色抓取 Hello。我已经尝试过一种笨拙的方式,它只是在我改变颜色时存储选定的单词,但是有没有一种方法可以一次抓取所有绿色文本?我试过谷歌搜索,但......它并没有真正想出任何好的方法。谁能指出我正确的方向?

4

1 回答 1

2

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

您需要获取对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");
        }
    }
}

这个例子简单地找到了第一个红色的单词,但是你可以很容易地遍历整个文档并找到你想要的所有单词......

于 2013-04-10T03:54:09.087 回答