Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change specific String attributes in StyledDocument

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.

like image 825
Mihai Andrei Rustiuc Avatar asked Feb 18 '23 22:02

Mihai Andrei Rustiuc


2 Answers

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.

like image 57
Gilbert Le Blanc Avatar answered Feb 28 '23 06:02

Gilbert Le Blanc


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

image

like image 30
trashgod Avatar answered Feb 28 '23 04:02

trashgod