Question

I'm working with a JTextPane.

JTextPane pane = new JTextPane();
String content = "I'm a line of text that will be displayed in the JTextPane";
StyledDocument doc = pane.getStyledDocument();
SimpleAttributeSet aSet = new SimpleAttributeSet();

If I add this aSet to the textpane's document like this:

doc.setParagraphAttributes(0, content.length(), aSet, false);

Nothing visible happens. No big surprise since I haven't set any custom attributes for aSet. However, if I allow aSet to replace the current ParagraphAttributes of doc like this:

doc.setParagraphAttributes(0, content.length(), aSet, true);

A lot of things happen. How can I get information on those default values of the JTextPane document? Particularly my problems is that when I'm defining a custom Font for aSet and set it to replace the current attributes, the font is displayed as if it was bold. StyleConstants.setBold(aSet, false); doesn't help.

Was it helpful?

Solution

I have looked at the source code to see what data structures are holding the information that you want. This is a modification of that code that prints the attributes for each paragraph.

int offset, length; //The value of the first 2 parameters in the setParagraphAttributes() call

Element section = doc.getDefaultRootElement();
int index0 = section.getElementIndex(offset);
int index1 = section.getElementIndex(offset + ((length > 0) ? length - 1 : 0));
for (int i = index0; i <= index1; i++)
{
    Element paragraph = section.getElement(i);
    AttributeSet attributeSet = paragraph.getAttributes();
    Enumeration keys = attributeSet.getAttributeNames();
    while (keys.hasMoreElements())
    {
        Object key = keys.nextElement();
        Object attribute = attributeSet.getAttribute(key);
        //System.out.println("key = " + key); //For other AttributeSet classes this line is useful because it shows the actual parameter, like "Bold"
        System.out.println(attribute.getClass());
        System.out.println(attribute);
    }
}

The output for a simple textPane with some text added through the setText() method gives:

class javax.swing.text.StyleContext$NamedStyle
NamedStyle:default {foreground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],size=12,italic=false,name=default,bold=false,FONT_ATTRIBUTE_KEY=javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=plain,size=12],family=Dialog,}

About your particular problem, looking at a related SO question I have been able to set the text of a paragraph to bold with:

StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aSet = sc.addAttribute(aSet,  StyleConstants.Bold,  true);

In this case the class of aSet is javax.swing.text.StyleContext$SmallAttributeSet which is not mutable (does not implement MutableAttributeSet). For your case something along the lines:

aSet.addAttribute(StyleConstants.Bold, true);

should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top