Search code examples
javaswingjtextpane

HTML JTextPane newline support


I'm using a JTextPane to edit HTML. When I enter newlines in the GUI component and call getText() on the JTextPane, I get a string with newline characters. If I then create a new JTextPane and pass that same text in, the newlines are ignored.

Why doesn't JTextPane insert a <br> tag when a newline is entered? Is there a good workaround for this?

    JTextPane test = new JTextPane();
    test.setPreferredSize(new Dimension(300, 300));
    test.setContentType("text/html");
    test.setText("Try entering some newline characters.");
    JOptionPane.showMessageDialog(null, test);
    String testText = test.getText();
    System.out.println("Got text: " + testText);
    // try again
    test.setText(testText);
    JOptionPane.showMessageDialog(null, test);
    testText = test.getText();
    System.out.println("Got text: " + testText);        

Sample output:

<html>
  <head>

  </head>
  <body>
    Try entering some newline characters.
What gives?
  </body>
</html>

I realize I could convert newlines to HTML line breaks before calling setText, but that would convert the newlines after the HTML and BODY tags as well, and seems dumb.


Solution

  • I've resolved this, the problem was the plain text I was passing in in setText. If I take out the call to setText, the result of JTextPane.getText() is nicely formatted HTML with line breaks correctly encoded.

    I believe when I call JTextPane.setText("Try entering some newline characters") it sets the HTMLDocument.documentProperties.__EndOfLine__ to "\n". This document property constant is defined here.

    The solution is to make sure you wrap your text in <p> tags when passing it to the JTextPane.setText() method (note, the style attribute is used for any subsequent paragraphs):

    textPane1.setText("<p style=\"margin-top: 0\">Try entering some newline characters</p>");
    

    Or, after you pass in plain text, replace the EndOfLineStringProperty (this is more of a hack, I wouldn't recommend it):

    textPane1.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "<br/>\n")