0

テキストの文字列があります:「これは |<スキー>| に行くための |<良い>| 山です。」

|<良い>|が欲しい と|<スキー>| 赤、斜体、FontSize 9 で表示されます。

個々の AttributeSet を設定しました

  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);

パターンを正しく見つける正規表現があります。しかし、複数の AttributeSet を同じ一致に設定しようとすると、最初の 1 つだけが正規表現を尊重します。他のものは、文字列全体に適用されます。クラス全体は次のとおりです。

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