0

我有一串文字:“这是一个 |<good>| 到 |<ski>| 的山。”

我想要|<好>| |<滑雪>| 显示为红色、斜体、FontSize 9。

我已经设置了单独的 AttributeSets

  StyleContext myProtected = StyleContext.getDefaultStyleContext();
  AttributeSet attR = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Foreground, Color.RED);
  AttributeSet attB = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Background, Color.BLUE);
  AttributeSet attI = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Italic, Boolean.TRUE);
  AttributeSet attS = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.FontSize, 9);

我有一个正确找到模式的正则表达式。但是,如果我尝试将多个 AttributeSets 设置为相同的匹配,则只有第一个尊重正则表达式。其他人只是将自己应用于整个字符串。这是整个班级:

class ElementHighlight2 extends DefaultStyledDocument {
  //private final  MutableAttributeSet XRED = new SimpleAttributeSet();

  StyleContext myProtected = StyleContext.getDefaultStyleContext();
  AttributeSet attR = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Foreground, Color.RED);
  //AttributeSet attB = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Background, Color.BLUE);
  AttributeSet attI = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Italic, Boolean.TRUE);
  AttributeSet attS = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.FontSize, 9);    

@Override
  public void insertString (int offset, String Pstr, AttributeSet RedBlue) throws BadLocationException
  {
   super.insertString(offset, Pstr, RedBlue);
   String text = getText(0, getLength());
   int pre = pipeCharEnd(text, offset);
   if (pre < 0) pre = 0;
   int post = pipeCharStart(text, offset + Pstr.length());
   int prewords = pre;
   int postwords = pre;

   while (postwords <= post) {
                if (postwords == post || String.valueOf(text.charAt(postwords)).matches("\\|")) {
                    if (text.substring(prewords, postwords).matches("(\\|\\<[^\\>]*\\>)"))
                        setCharacterAttributes(prewords, postwords - prewords +1, attR, false);
                        setCharacterAttributes(prewords, postwords - prewords +1, attI, false);
                        setCharacterAttributes(prewords, postwords - prewords +1, attS, false);

                    prewords = postwords;
                }
                postwords++;
            }
  }

如果有人可以帮助我学习我尚未发现的最佳实践来实现这一目标,我将不胜感激。

4

1 回答 1

0

我认为您可以创建一个组合属性集,而不是创建单个属性并将它们与setCharacterAttributes组合:

AttributeSet attR = myProtected.addAttribute(myProtected.getEmptySet(), StyleConstants.Foreground, Color.RED);
AttributeSet attI = myProtected.addAttribute(attR, StyleConstants.Italic, Boolean.TRUE);
AttributeSet attS = myProtected.addAttribute(attI, StyleConstants.FontSize, 9);    

然后只应用组合的attS.

于 2015-01-08T14:17:28.760 回答