Change specific String attributes in StyledDocument

爷,独闯天下 提交于 2019-12-07 08:16:53

问题


I am trying to create a text editor. I am using a JTextPane with a StyledDocument. What I am trying to implement is a way to change the attributes of selected text.

This works in the following way : the user inputs the desired text. Afterwards, he can change any String's attributes (Font family, font size, whether it is bold/italic or not) by selecting it and pressing a button, where by means of checkboxes and dropdown lists would select the desired changes.

Is it possible for me to change that selected String's attributes without the need to rebuild the document? I have been searching but was unable to find a proper solution.


回答1:


You can use the actions provided by the StyledEditorKit, seen here and discussed in How to Use Editor Panes and Text Panes.




回答2:


You would use the setCharacterAttributes method of StyledDocument.

Here's an example from one of my Swing applications, that highlights the text with a highlight color.

        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(
                SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, highlightColor);
        cobolProgram.setCharacterAttributes(offset, length, aset,
                false);

You can use other StyleConstants to change other style attributes.




回答3:


In my case, I "cleaned" the style when the user changes the text:

StyledDocument doc = tf.getStyledDocument();

//clean style
doc.setCharacterAttributes(0, sb.length(), DEF, true); 


来源:https://stackoverflow.com/questions/14198787/change-specific-string-attributes-in-styleddocument

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