0

I have a JTextPane that displays some text. It is generated dynamically. The program receives, from a socket, the style of the text and the text itself.

As an example, I want some parts of the text to be bold, some others to be centered, and some parts to be both bold and centered. I set a style with this code

doc.insertString(doc.getLength(), text, boldText);

Is there a way to do something like:

doc.insertString(doc.getLength(), text, boldText + centeredText);

I don't want to create a separate SimpleAttributeSet for every combination of Styles that I will need, as in the real program there will be many more options and it would be so hard to read plus it would drive me crazy.

Thanks

camickr
  • 321,443
  • 19
  • 166
  • 288

1 Answers1

1

I don't want to create a separate SimpleAttributeSet for every combination of Styles

Why? That is the way HTML works. You can set attributes for individual tags like h1, h2, h3 etc.

Why would your app be different?

You will get different types of text from your socket so part of the text should include the "type" of text so you can use the appropriate style.

So you should really have one set of attributes for each type of text you can receive so you have a one-to-one mapping which is easy to control.

However, a SimpleAttributeSet has an addAtributes(...) method, so there is no reason you can't create an attribute set with the attributes of two individual attribute sets.

Something like:

SimpleAttributeSet combined = new SimpleAttributeSet();
combined.addAttributes( boldText );
combined.addAttributes( centeredText );
doc.insertString(doc.getLength(), text, combined);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • In html I could put multiple classes like

    , but jTextPane is limited to html 3.2, and there are multiple things that I can't make with it. I would like to know if there is a way to do something like that without creating a new SimpleAttributeSet as you did, but there doesn't seem to be a way to do so. Thank you anyways :)

    – Alex Ghilas Mar 18 '21 at 22:18