javastringswingjtextpanestyleddocument

JTextPane additional empty lines


I have a JTextPane I set its text with the following method.

public void setConfigPaneText(String content, Style style)
{
    StyledDocument logDoc = configPane.getStyledDocument();

    if(style == null)
    {
        style = configPane.addStyle("Style", null);
        StyleConstants.setForeground(style, Color.white);
        StyleConstants.setBold(style, true);
    }

    try 
    {
        configPane.setText(null);
        logDoc.insertString(logDoc.getLength(), content, style);
    }
    catch (BadLocationException e1)
    {
        e1.printStackTrace();
    }
}

I build the content String like this:

            if(f.exists())
            {
                Scanner scan = new Scanner(f);
                while(scan.hasNextLine()) 
                {
                    strbld.append(scan.nextLine()+"\n");
                }                   
                TopologyMain.nodes.get(i).setPtpConfig(strbld.toString()); // output
                scan.close();
            }

So I have this string appear in the JTextPane correctly, the problem is when I save the content of the JTextPane into a txt file and reload it to the JTextPane, one new empty row appears after every line.

Picture here: http://postimg.org/image/76z69oe7x/

Code doing save...

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileChooser.getSelectedFile().getAbsolutePath())));
    out.print(configPane.getText());
    out.close()

and load:

if(filetmp.exists()) 
{
    Scanner scan;
    try 
    {
        scan = new Scanner(filetmp);

        while(scan.hasNextLine()) 
        {
            strbld.append(scan.nextLine()+"\n");
        }                   

        setConfigPaneText(strbld.toString(), null);

        scan.close();
    } 
    catch (FileNotFoundException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 }

Without the /n in this method it looks like this: http://postimg.org/image/kn38ja8ov/

The cause of the problem can be that I have an additional "\r" character at the end of my lines as it can be seen here: http://postimg.org/image/9ny41rz3z/. But I do not know where they come from.

Thanks for your time!


Solution

  • Solution from Gavi in the comments:

    The problem's cause was that I had multiple CR ( "\r" ) characters as it can be seen here. You can check the output txt file with notepad++'s show all character function to find it out yourself. Then check up all code parts relate to the JTextPane or to the String you use as content to find the additional CRs and remove them.