Getting style from any offset in JTextPane

南楼画角 提交于 2019-12-01 08:15:03

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/4819780/getting-style-from-any-offset-in-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!