我有一串文字:“这是一座山。”
我想要显示为红色,斜体,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++;
}
}如果有人能帮助我学习到我还没有发现的最佳实践,我将非常感激。
发布于 2015-01-08 14:17:28
与其创建单个属性并将它们与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。
https://stackoverflow.com/questions/25231788
复制相似问题