ColorPane - 可以抓取不同角色的字符串?

问题描述 投票:0回答:1

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

它使用这种方法

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

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

java swing jtextpane styleddocument
1个回答
2
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.