【发布时间】:2014-08-19 08:23:41
【问题描述】:
我有一个 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/。但我不知道它们来自哪里。
感谢您的宝贵时间!
【问题讨论】:
标签: java string swing jtextpane styleddocument