javaswingrichtextjeditorpane

How do I check if a certain index in a jEditorPane contains a character that is bolded, italicized, or underlined?


I've made a program that loads a text document into a jEditorPane. Some of the text in the document is bolded, italicized, or underlined, and I want to know how to check if a particular index in the text contains one of these three attributes. For instance, if I store the first character of the text in a variable as follows:

char chr = jEditorPane1.getDocument().getText(0, 1).charAt(0);

How do I then check if the character in chr has been bolded, italicized, or underlined?


Solution

  • StyledDocument doc = (StyledDocument)jEditorPane1.getDocument()
    Element textElem = doc.getCharacterElement(offset);
    StyleConstants.isBold(textElem.getAttributes());
    StyleConstants.isItalic(textElem.getAttributes());
    

    Alternatively if caret is positioned in the offset you can get InputAttributes from the kit.

    AttributeSet attrs = ((StyledEditorKit)jEditorPane1.getEditorKit()).getInputAttributes();
    StyleConstants.isBold(attrs);