Set JEditorPane Height According To Content’s Height

Setting a JEditorPane‘s height to adjust to the total height of its content is no easy task. There is no method associated with the class to actually do that. You would have to dig deeper on its associated classes in order to do a workaround. However, I was lucky to find a dirty hack in the internet on how to accomplish this. Took quite some time for me to find this amongst the various forums I visited.

Here is the code:

The method has extra parameter width which is important because JEditorPane by default has word wrapping activated so the resulting height will depend heavily based on the width of the JEditorPane.

If by chance your JEditorPane uses an editor kit like RTFEditorKit or StyledEditorKit, you would need to get the javax.swing.text.Document object and convert that to its String value before passing it as the second parameter of the method.

I also ran into a situation where my JEditorPane uses HTML content. So I really had problems when getting the height because HTML tags are included in the setText() method. To properly get the height of the JEditorPane with HTML content, do this.

Related Posts Plugin for WordPress, Blogger...

4 comments

Leave a Reply

Your email address will not be published. Required fields are marked *