Search code examples
javaswingtextnewlinejeditorpane

Newlines in JEditorPane


I am currently using a JEditorPane to display text that is being read from a Socket. I create the JEditorPane, get its Document and add the text as it comes using

document.insertString(document.getEndPosition().getOffset(), string, null); 

This works as expected, except that when It encounters a '\n' (The character being used for a newline), it seems to ignore it (i.e. not print anything), and everything comes out on one line. I've looked around for a solution but I can't seem to find anything that works (Tried replacing '\n' with <br>, didn't help, it just printed out the <br>.


Solution

  • It works as you expected.

    Here is the code.

    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    doc.insertString(doc.getEndPosition().getOffset(), "test\n", null);
    

    the complete code.

        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
        jScrollPane1.setViewportView(jEditorPane1);
    
        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    
        pack();
    
    1. Check whether any other property has been set on the editorpane.
    2. What editor kit are you using?
    3. try printing the input and ensure that it comes with '\n'

    You can also use,

        doc.insertString(doc.getLength(), "test\n", null);