Martin
Martin

Reputation: 3615

Getting style from any offset in JTextPane

Is there a way to get Style, a style name or just even compare whether Style at a certain position of JTextPane with the style I gave the text when inserting? Because for my purpose I created custom JTextPane, StyledDocument and DocumentFilter. So I could choose Style to be used for say regular letters and another Style for numbers. I have also toggle button which while toggled sets DocumentFilter to format numbers differently and while not toggled numbers format regularly so at the end you can't distinguish which numbers have been affected just according to JTextPane's getText() method. Therefore the only way would be to compare styles which I have both regular and special number style as constants. Only thing I need to come up with is how to get Style for each character.

I know there is JTextPane's method to get AttributeSet from the caret's position called getCharacterAttributes() but I think it's no use for my issue.

Is it necessary to include code example? I don't think it's difficult to imagine. If you want me I will include it though.

Any input would be appreciated. Thanks!

Upvotes: 2

Views: 2637

Answers (1)

dogbane
dogbane

Reputation: 274612

Try calling StyledDocument.getCharacterElement(pos) to get the character element at that position and then call Element.getAttributes() to get its attribute set.

The AttributeSet contains styles which you can retrieve using methods provided by StyleConstants.

Upvotes: 9

Related Questions