I had a problem this weekend with the JEditorPane line wrap (word wrap), where it was wrapping lines on the right margin right in the middle of words. Wherever my sentence hit the right margin, that's where the line wrapped (with no consideration for word boundaries), leaving me with lines that looked like this:
Four score and seven y ears ago, our fathers
(I'm pretty sure Lincoln didn't say "ears ago".)
Now, I don't have a detailed technical solution for how to solve this problem with the JEditorPane but I can tell you what I did to fix the problem: I traded out my JEditorPane for a JTextPane. JTextPane is a subclass of JEditorPane, and switching to JTextPane immediately fixed the line wrapping problem.
At this point I don't know why switching to a JTextPane solves this problem, but I can tell you two things I've found so far:
- JTextPane requires that its Document be a StyledDocument and Swing supplies a default implementation of this interface, named DefaultStyledDocument.
- The JTextPane requires that its EditorKit be an instance of a StyledEditorKit.
I'm 98% sure that this solution comes from the StyledEditorKit, but without digging into the code, I won't know for sure. But here is a short blurb from the StyledEditorKit javadoc:
This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document. This implementation provides a default implementation which treats text as styled text and provides a minimal set of actions for editing styled text.
Again, at the moment I'm not very concerned about the details of the solution; I'm just glad that switching to the JTextPane easily solved the JEditorPane wrap problem.