javajeditorpanedocumentfilterhtmleditorkit

JEditorPane with HTMLEditorKit returning newline character instead of <br> tag


I’m trying to work around an inconsistency when using JEditorPane.getText() with HTMLEditorKit installed.

I can use JEditorPane.setText to pass an HTML string containing < br> tags, and when I use getText() those new-lines appear correctly as < br>. But when the user enters a new-line in the JEditorPane, the getText() returns a “/n” character rather than a < br> tag. My custom HTML parser can’t distinguish between the users “/n” characters and the “/n” characters added –seemingly – to make the HTML string look pretty. An example:

If the user enters some text, the JEditorPane.getText() procedure will return something like this:

<html>
  <head>

  </head>
  <body>
    I've written some text! Indeed so much text that this line is probably 
    going to word wrap when I run the getText procedure!

And now I just hit enter a few times! I wonder what will happen if it wraps 
    another time? WHAM.
And I'll hit enter once more for good measure.
  </body>
</html>

Whereas I’d expect this to show up as:

<html>
  <head>

  </head>
  <body>
    I've written some text! Indeed so much text that this line is probably 
    going to word wrap when I run the getText procedure!<br><br>And now I 
    just hit enter a few times! I wonder what will happen if it wraps 
    another time? WHAM.<br>And I'll hit enter once more for good measure.
  </body>
</html>

Is there any way to have < br> be inserted in the getText string when the user hits enter? My first attempt was to use a documentFilter, but the documentation says I’m only aloud to use the insertString or the filterBypass within the filter, therefore I can’t use the setText (“< br>”) route. After tons of reading, I’m thinking another option would be to extend HTMLEditorKit and override the read procedure? JTextComponents are new to me, so that’s way over my head. Are there other options? Or resources?

Thanks!


Solution

  • Got it.

    My initialization looked like this:

    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = new HTMLDocument();
    editor_pane.setEditorKit(kit);
    editor_pane.setDocument(doc);
    

    But it seems this is not sufficient for the document to handle all user input. Unfortunately it is enough to handle StyledEditorKit.BoldAction or StyledEditorKit.ItalicAction correctly, which is why I didn't think the problem was in the initialization.

    HTMLEditorKit kit = new HTMLEditorKit();
    editor_pane.setEditorKit(kit);
    editor_pane.setContentType("text/html");
    

    I changed the initialization to the above, as recommended in the article @StanislavL shared. With this correction, the JEditorPane now creates new paragraphs when the user hits enter, which is good enough for my purposes. Thanks for the help!