Search code examples
javahtmlswingjeditorpanehtmleditorkit

Formatting text with HTML in a JEditorPane?


I am trying to make a simple email client in Java Swing.

I want to allow users to format their email in any way they want, like making some parts of the text bold, other parts italic, etc. In other words, I am trying to make a WYSIWYG editor. The formatting is done in HTML. I am using JEditorPane to display the text.

I have tried adding tags myself to the text directly by using setText and getText methods of JEditorPane. I could make it work for basic formatting, but it is quite difficult to handle complex formatting. (trying to remove tags from multi-tagged elements, for example)

Is there an easier way to accomplish this? I have looked at HTMLEditorKit but it seems like it does not support adding tags to and/or replacing a specific string.

Thanks in advance.


Solution

  • The HTMLEditorKit comes with some default Actions that allow you to do some basic styling of the text with the click of a menu item (or button). Take a look at the example in the section from the Swing tutorial on Text Component Features.