我有一个 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/ .但我不知道它们来自哪里。
感谢您的宝贵时间!
最佳答案
这里的问题是你添加了两次“\n”。一次构建内容字符串,一次加载文件。如果您删除加载函数中的“\n”,您应该会看到没有额外空行的文本。
关于java - JTextPane 额外的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25378743/