Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word Wrap in JEditorPane and System Font

I'm wanting to create a large text field for a user to type something in. I also want it to use the default system font to match the look and feel that is expected. So I tried to use a JEditorPane with the default constructor, which uses plain text encoding.

JEditorPane editorPane = new JEditorPane();
editorPane.setText(gettysburgAddress);

enter image description here

The trouble with this is that plain text encoding doesn't wrap to a newline at the end of each word, only when it runs out of characters.

I tried using the HTML encoding, which word wraps:

JEditorPane editorPane = new JEditorPane("text/html", "");
editorPane.setText(gettysburgAddress);

enter image description here

This has the word wrap, but it defaults to a different font than the default for the system (Helvetica on Mac OS X, which I don't want.

How can I get the best of both worlds: word wrap and the system default font? I don't need any special formatting or anything for this, so plain text encoding will do if it is possible.

like image 573
Thunderforge Avatar asked Mar 24 '23 21:03

Thunderforge


1 Answers

If all that is needed is a word-wrapped JEditorPane using the system font, and you don't need anything special like stylized text or images, then it's probably best just to switch to a JTextArea, which is a text component for doing just plain text. It doesn't word wrap by default, but it's easy to make it happen:

JTextArea textArea = new JTextArea();
textArea.setLineWrap(true); //Makes the text wrap to the next line
textArea.setWrapStyleWord(true); //Makes the text wrap full words, not just letters
textArea.setText(gettysburgAddress);

If you absolutely must use a JEditorPane for some reason, you'll have to roll up your sleeves and make some changes to the way that the JEditorPane is rendering text. On the plus side, you have several different methods to choose from. You can:

  • Set the encoding to HTML (which word wraps) and use CSS to specify the font (described here)
  • Set the encoding to RTF (which word wraps) and modify the font values of the underlying RTFEditorKit (described here)
  • Create a SimpleAttributeSet and use it when adding strings to specify that they should be displayed in that way (described here)
like image 116
Thunderforge Avatar answered Apr 06 '23 04:04

Thunderforge