将多个StyleConstants添加到AttributeSet

时间:2014-08-10 18:35:31

标签: java addattribute defaultstyleddocument

我有一串文字:"这是|< good> |山到|< ski> |上"

我希望 |< 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++;
            }
  }

如果有人能帮助我学习我尚未发现的最佳实践,我将非常感激。

1 个答案:

答案 0 :(得分: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