0

我使用此代码片段在 MS Word 文件中设置颜色文本

CharacterRun r = paragraph.getCharacterRun(2).insertBefore("x");
r = r.insertBefore("y");
r.setColor(6);
r.insertBefore("z);

我想将颜色设置为仅“y”字符,但我得到的结果是所有“x”、“y”、“z”都设置为红色。我在哪里错了?如何将颜色设置为仅“y”字符 - 第二个 CharacterRun。

提前致谢

4

1 回答 1

0

我想迟到总比没有好:您可能正在为整个包含运行设置颜色。你需要做的是:

  • 从当前运行中删除溢出的文本
  • 在相邻运行中添加溢出的文本
  • 为当前运行着色

这是一个例子

private void highlightSubsentence(String currentRunText, String sentence, CharacterRun currentRun, int runIndex, Paragraph p, HighlighterColor color) {
        int sentenceBeginIndex = currentRunText.indexOf(sentence, 0);
        int sentenceLength = sentence.length();
        String leftSentence = currentRunText.substring(0, sentenceBeginIndex);
        String rightSentence = currentRunText.substring(sentenceBeginIndex + sentenceLength);
        boolean leftOverflow = sentenceBeginIndex > 0;
        boolean rightOverflow = sentenceBeginIndex + sentenceLength < currentRunText.length();
        boolean isInTable = p.isInTable();
        if (rightOverflow && !isInTable && runIndex + 1 < p.numCharacterRuns()) {
            currentRun.replaceText(sentence + rightSentence, sentence);
            p.getCharacterRun(runIndex + 1).insertBefore(rightSentence);
        }
        if (leftOverflow && !isInTable && runIndex > 0) {
            currentRun.replaceText(leftSentence + sentence, sentence);
            p.getCharacterRun(runIndex - 1).insertAfter(leftSentence);
        }
        currentRun.setColor(6);
    }
于 2018-08-24T10:27:47.247 回答