Articles Projects Tips Downloads Contacts About

Loosing last empty paragraph in HTML from JEditorPane fix.

JTextPane with HTMLEditorKit set ignores/removes empty last empty paragraphs when we try to get html content via getText() method. The behavior comes from the protected boolean inRange(Element next) method of the HTMLWriter. Javadocs for the method states - "This method determines whether the current element is in the range specified". Actually the priblem is the last paragraph start/end offset. Structure of the document is organized in this way to have at least one element so the last paragraph's start offset equals to the document's length. So the last paragraph isn't included in the saving procedure.

To fix this we have to change a bit establishing end offset in the write() method. The code below shows correct behaviour.

        JEditorPane edit=new JEditorPane() {
            public void write(Writer out) throws IOException {
                Document doc = getDocument();
                try {
                    getUI().getEditorKit(this).write(out, doc, 0, doc.getLength()+1); //the last +1 did the trick
                } catch (BadLocationException e) {
                    throw new IOException(e.getMessage());
        edit.setEditorKit(new HTMLEditorKit());
        edit.setText("<html>\n" +
                "<head>\n" +
                " \n" +
                "</head>\n" +
                "<body>\n" +
                "<p style='margin-top: 0'>" +
                " \n" +
                "</p>\n" +
                "</body>\n" +
                "</html>\n" +
                "\n" +