I have a string of text: "This is a |<good>| mountain to |<ski>| on."
I want |<good>| and |<ski>| to appear red, italic, FontSize 9.
I've set individual 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);
and I have a regex that finds the patterns correctly. But if i try to set multiple AttributeSets to the same match, only the first one respects the regex. The others just apply themselves to the whole string. Here's the whole class:
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++;
}
}
If somebody could help me learn the best practice that I have not yet discovered to achieve this, I will be most grateful.