2

My JEditorPane automatically wraps words; I don't want that. All I want is a horizontal bar to appear that allows the user to write as much as desired. How can I do that? I have tried several methods. I have overridden the getScrollableTracksViewportWidth(), but that didn't help. Does any one know how I can turn off the word wrap?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
zukes
  • 381
  • 2
  • 7
  • 16
  • 2
    If you don't need the features from `JEditorPane`, you could use a `JTextArea` which suppors a `setLineWrap()` method. –  Jan 22 '12 at 12:44
  • 1
    cross posted: http://www.coderanch.com/t/565180/GUI/java/turn-off-word-wrap-jeditorpane – camickr Jan 22 '12 at 17:12

4 Answers4

5

A quick google search lead me to this page, which implements it by subclassing the text pane and overriding the getScrollableTracksViewportWidth() method:

// Override getScrollableTracksViewportWidth
// to preserve the full width of the text
public boolean getScrollableTracksViewportWidth() {
    Component parent = getParent();
    ComponentUI ui = getUI();

    return parent != null ? (ui.getPreferredSize(this).width <= parent
        .getSize().width) : true;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • The example from the page linked to in this example works in general, but the caret gets cut off as you type new text that goes beyond the bounds. (ie once the scroll bar shows up). – Amber Oct 09 '17 at 17:34
3

Try this http://java-sl.com/wrap.html

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • 1
    That link no longer works for me. Sad the data was not copied over as it seems to have been the accepted answer. – Queeg Nov 28 '22 at 08:29
  • @stanislavl At least there's the wayback machine : https://web.archive.org/web/20220203131713/http://java-sl.com/wrap.html – bric3 Jul 18 '23 at 13:04
2

If you can control the text which is going into, and you are using features of JEditorPane, you can mark the code via html, and use white-space:nowrap; stile property.

jEditorPane1.setContentType("text/html");
StringBuilder sb = new StringBuilder();
sb.append("<div style='");
   if (!wordWrap.isSelected()) {  //some checkbox
       sb.append("white-space:nowrap;");
   }
       sb.append("font-family:\"Monospaced\">'");
sb.append("your very interesting long and full of spaces text"); 
/*be aware, more then one space in row will be replaced by single space
  to avoid it you need to substitute by &nbsp;.
  Also rememberer that \n have to be repalced by <br>
  so filering like:
            line = line.replaceAll("\n", "<br>\n"); //be aware, <br/> do not work
            line = line.replaceAll("  ", "&nbsp; ");
            line = line.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
  may be usefull.*/
sb.append("</div>");
jEditorPane1.settext(sb.toString()); //jeditor pane do not support addition/insertion of text in html mode
judovana
  • 418
  • 2
  • 6
-1

why don't you use a jTextField?

it's only one line.

Jill
  • 539
  • 1
  • 5
  • 12