Search code examples
javaswingline-breaksjtextarea

Enter key doesn't make line break in JTextArea backed with HTMLDocument


Code below displays text which you can edit, but when you press ENTER line break doesn't appear.

Why and how to fix?

This is because HTMLDocument is used as a model. If default model is used, then line breaks are inserted and displayed.

public class JTextAreaTry extends JFrame {

    private HTMLDocument doc = new HTMLDocument();

    {
        try {
            doc.insertString(0, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
                + "Phasellus tincidunt, neque ac lobortis viverra, nunc erat convallis leo, sit amet varius purus metus ac dolor. "
                + "Morbi pellentesque velit eu ornare pellentesque. "
                + "Sed lectus orci, sollicitudin non nunc in, vehicula mollis massa. "
                + "Sed a est ac arcu auctor interdum. "
                + "Duis at mauris pellentesque, semper massa nec, cursus nulla. "
                + "Fusce sed rhoncus nisl. Sed et sollicitudin mauris, a laoreet nulla. "
                + "Donec interdum volutpat orci, non placerat odio ultrices non.", null);
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }

    JTextArea textArea;

    {
        textArea = new JTextArea();
        textArea.setDocument(doc); // comment this
        textArea.setLineWrap(true);
        add(textArea);
    }

    public static void main(String[] args) {
        JFrame frame = new JTextAreaTry();

        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.setVisible(true);
    }

}

Solution

  • JTextArea is designed for plain text, not styled text. If you are about to use HTML-formatted text, then please consider using JEditorPane / JTextPane, which have built-in support for HTML (and line-breaking works as expected when pressing the Enter key). Example below:

    JEditorPane ep = new JEditorPane(); 
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc = new HTMLDocument();
    ep.setEditorKit(kit);
    ep.setDocument(doc);
    kit.insertHTML(doc, doc.getLength(), "<b>Hello world!</b>", 0, 0, null);