Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Bringer128 found the problem above, but I'll just clarify a little more.</p> <p>When a Style is added to a JTextPane, the String that is passed as an argument is actually placed in the Style as an Attribute (not surprisingly, the NameAttribute). When the Style is applied to a range of characters, the NameAttribute is applied along with any other Attributes that have been set on the Style. So when my BOLD Style was applied, every character in that range had its BoldAttribute set to true and its NameAttribute set to "Bold". Then, when my ITALIC Style was applied, every character had its ItalicAttribute set to true, and then its NameAttribute set to "Italic". Then, when containsAttributes() checked if all Attributes in my BOLD Style were applied to those characters, it returned false because their NameAttributes had been changed from "Bold" to "Italic". I hope that didn't confuse anyone.</p> <p>Here is my work around (I think it's actually simpler than the original code). The gist of it is I never use Styles or JTextPane.addStyle() at all; I just keep constant MutableAttributeSets.</p> <pre><code>import javax.swing.JTextPane; import javax.swing.text.StyleConstants; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; public class StyleBugFix { public static void main(String[] args) { JTextPane textPane = new JTextPane(); textPane.setText("This is a test string"); StyleConstants.setBold(BOLD, true); StyleConstants.setItalic(ITALIC, true); int start = 5; int end = 10; textPane.getStyledDocument().setCharacterAttributes(start, end - start, BOLD, false); textPane.getStyledDocument().setCharacterAttributes(start, end - start, ITALIC, false); for(int i = start; i &lt; end; i++) System.out.println(textPane.getStyledDocument().getCharacterElement(i).getAttributes() .containsAttributes(BOLD)); //all now print true } private static final MutableAttributeSet BOLD = new SimpleAttributeSet(); private static final MutableAttributeSet ITALIC = new SimpleAttributeSet(); } </code></pre> <p>Thanks again to Bringer128 for all his help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload