I’ve been using a JTextPane (or my sub-classed version of one) in an application I’ve been writing, and so I’ve been working with Styles. My program wasn’t acting the way I wanted, and I tracked the behavior to what I think is a bug in the AttributeSet.containsAttributes(AttributeSet attributes) method. I wrote the following short program to illustrate it:
import javax.swing.JTextPane;
import javax.swing.text.StyleConstants;
import javax.swing.text.Style;
public class StyleBug {
public static void main(String[] args) {
JTextPane textPane = new JTextPane();
textPane.setText("This is a test string");
Style bold = textPane.addStyle(BOLD, null);
StyleConstants.setBold(bold, true);
Style italic = textPane.addStyle(ITALIC, null);
StyleConstants.setItalic(italic, true);
int start = 5;
int end = 10;
textPane.getStyledDocument().setCharacterAttributes(start, end - start, textPane.getStyle(BOLD), false);
textPane.getStyledDocument().setCharacterAttributes(start, end - start, textPane.getStyle(ITALIC), false);
for(int i = start; i < end; i++)
System.out.println(textPane.getStyledDocument().getCharacterElement(i).getAttributes()
.containsAttributes(textPane.getStyle(BOLD))); //all print false
}
private static final String BOLD = "Bold";
private static final String ITALIC = "Italic";
}
Is this a bug, or am I missing something here?
If I comment out this line:
Then it prints true for all of the elements. According to the Javadoc for
setCharacterAttributesit uses all of the Attributes from the Style you are passing in, so you are simply overriding theBOLDselection with theITALICselection.EDIT:
I pulled up the debugger and got this array of attributes for
getCharacterElement(5).As you can see, the attributes are ordered in groups of 2.
italicis set to true,boldis set to true, and thenameis set to"Italic". This likely means that only one name is allowed for a named attribute set for a character. Note that the unnamed attributes were merged correctly, so it is behaviourally what you want even if you can’t see if a particular named attribute is applied to a character.