0
votes

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);
    }

}