Word Wrap in JEditorPane and the system font

I want to create a large text box for user input of a type. I also want it to use the default system font so that it matches the expected look and feel. So I tried using JEditorPane with a standard constructor that uses text encoding.

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

enter image description here

The problem is that a simple text encoding is not wrapped to a new line at the end of each word, only when it runs out of characters.

I tried using HTML encoding that wraps words:

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

enter image description here

This has the word wrap, but by default it is different from the default font 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 default font for the system? I don't need any special formatting or anything like that, so a simple text encoding will do if possible.

+4
source share
1 answer

If all you need is a JEditorPane wrapped in words using a system font and you don’t need anything special like stylized text or images, then it is probably best to switch to JTextArea , which is the text component for plain text. By default, it does not carry the word, but it is easy to do:

 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 for some reason you need to use JEditorPane, you will have to roll up your sleeves and make some changes to the way text is displayed in JEditorPane. On the plus side, you have several different ways to choose. You can:

  • Set the encoding to HTML (which wraps words) and use CSS to specify the font (described here )
  • Set the encoding to RTF (which words wrap) and change the font values ​​for the base RTFEditorKit (described here )
  • Create a SimpleAttributeSet and use it when adding rows to indicate that they should be displayed this way (described here )
+6
source

Source: https://habr.com/ru/post/1481675/


All Articles