代码如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleContext;
import javax.swing.text.rtf.RTFEditorKit;
public class Test {
public static void main(String[] args) {
InputStream in = null;
try {
in = new FileInputStream("bbb.rtf");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DefaultStyledDocument doc = new DefaultStyledDocument(new StyleContext());
RTFEditorKit kit = new RTFEditorKit();
try {
kit.read(in, doc, 0);
} catch (IOException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
System.out.println("Reading, Doc length = " + doc.getLength());
JFrame jframe = new JFrame();
JTextPane jtp = new JTextPane();
jtp.setDocument(doc);
jframe.add(jtp);
jframe.setSize(400, 200);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
}
结果在JTextPane中显示比rtf文档中末尾多了一个回车,经研究发现是由于setDocument方法引起的。
其方法说明是 Associates the editor with a text document. This must be a StyledDocument
.
我想是Associates的缘故吧,document本身末尾含回车,JTextPane中也是有回车的,因此组合一起就多了一个回车,但是如何解决这个问题呢?
2009.11.11 14:38编辑添加:
保证不多出换行的一个权宜办法:
try {
jtp.getDocument().insertString(0, doc.getText(0, doc.getLength() - 1), null);
} catch (BadLocationException e) {
e.printStackTrace();
}
此段用来替换
jtp.setDocument(doc);
至于insertString之后的文字无格式,可以通过构造insertString方法的第三参数AttributeSet来添加,此处为null,例如:
SimpleAttributeSet attrset = new SimpleAttributeSet();
StyleConstants.setForeground(attrset, Color.red);
StyleConstants.setUnderline(attrset, true);
StyleConstants.setItalic(attrset, true);
StyleConstants.setFontSize(attrset, 24);
至于其与原先doc的格式关联,还未找到。