-1

Consider the code,

Question #1

StyledDocument doc=textPane.getStyledDocument();
SimpleAttributeSet attrib=new SimpleAttributeSet();
attrib.addAttribute(StyleConstants.CharacterConstants.Alignment,StyleConstants.ALIGN_RIGHT);
doc.insertString(0,"This is sample text",attrib);

Why am i not able to get the alignment? and why i am able to get it by doing this

doc.setParagraphAttributes(0,doc.getLength(),attrib,false);

Question #2

attrib.addAttribute(StyleConstants.ColorConstants.Background,Color.LIGHT_GRAY);
doc.setParagraphAttributes(0,doc.getLength(),attrib,false);

Why am i not able to get the background color? and why i am able to get it by doing this

doc.insertString(0,"This is sample text",attrib);

Question #3

When can i get both working together i.e. text with a background and right alignment except using this way,

doc.insertString(0,"This is sample text",attrib);
doc.setParagraphAttributes(0,doc.getLength(),attrib,false);
JavaTechnical
  • 5,807
  • 8
  • 40
  • 79

1 Answers1

3

The issue is mixing paragraph and text attributes. There are two groups of attributes character attributes - font, font size, font color etc. and paragraph attributes like alignment, indents, line spacing, tab stops etc.

Bot the groups are applied to different levels of hierarchy (Document structure levels). Character attributes are applied to leaves (text elements) but paragraph attributes are applied to parents of the leaves (paragraph elements).

So StyledDocument has 2 methods setCharacterAttributes and setParagrapphAttributes to apply the attributes to proper level.

Thus when you insert string attributes are applied to leaves so only character attributes has meaning.

StanislavL
  • 55,186
  • 9
  • 58
  • 88