1

我有一个 JTextPane 我用以下方法设置它的文本。

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

我像这样构建内容字符串:

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

所以我让这个字符串正确出现在 JTextPane 中,问题是当我将 JTextPane 的内容保存到 txt 文件中并将其重新加载到 JTextPane 时,每一行之后都会出现一个新的空行。

图片在这里: http: //postimg.org/image/76z69oe7x/

代码保存...

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

并加载:

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

在这个方法中没有 /n 它看起来像这样: http: //postimg.org/image/kn38ja8ov/

问题的原因可能是我在行尾多了一个“\r”字符,如下所示:http: //postimg.org/image/9ny41rz3z/。但我不知道它们来自哪里。

谢谢你的时间!

4

3 回答 3

3

这里的问题是您添加了两次“\n”。一次是在您构建内容字符串时,一次是在您加载文件的位置。如果您删除加载函数中的“\n”,您应该会看到没有额外空行的文本。

于 2014-08-19T08:27:55.703 回答
0

在您的加载功能中,您不应该为每个扫描行添加换行符,试试这个:

while(scan.hasNextLine()) 
{
  strbld.append(scan.nextLine());
} 
于 2014-08-19T08:31:18.727 回答
0

Gavi在评论中的解决方案:

问题的原因是我有多个 CR ( "\r") 字符,可以在此处看到。您可以使用 notepad++ 的显示所有字符功能检查输出的 txt 文件以自行查找。然后检查与 JTextPane 或用作内容的字符串相关的所有代码部分,以查找其他 CR 并删除它们。

于 2014-08-19T11:08:24.683 回答