将 RTF 加载到 JTextPane

load RTF into JTextPane

我在文本编辑器程序中创建了一个 class 类型的 JTextPane。它具有从我的主要 JTextPaneClass 继承的文本和富文本的子class。但是,我无法将 RTF 加载到我的富文本中,因为读取文件输入流的方法不在 superclass JTextPane 中。那么如何将富文本读入 jtextpane 呢?这看起来很简单,我一定遗漏了一些东西。我看到很多使用 RTFEditorKit 并填充到 JTextPane 的示例,但当它实例化为 class.

时却没有
public class RichTextEditor extends TextEditorPane {

private final String extension = ".rtf";
private final String filetype = "text/richtext";

public RichTextEditor() {
    // super( null, "", "Untitled", null );
    super();
    // this.setContentType( "text/richtext" );
}

/**
 * Constructor for tabs with content.
 * 
 * @param stream
 * @param path
 * @param fileName
 * @param color
 */
public RichTextEditor( FileInputStream stream, String path, String fileName, Color color, boolean saveEligible ) {
    super( path, fileName, color, saveEligible );
    super.getScrollableTracksViewportWidth();
    //RTFEditorKit rtf = new RTFEditorKit();
    //this.setEditorKit( rtf );
    setEditor();
    this.read(stream, this.getDocument(), 0);
    //this.read( stream, "RTFEditorKit" );
    this.getDocument().putProperty( "file name", fileName );
}



private void setEditor() {
    this.setEditorKit( new RTFEditorKit() );

}

行:

this.read(stream, this.getDocument(), 0);

告诉我

The method read(InputStream, Document) in the type JEditorPane is not applicable for the arguments (FileInputStream, Document, int)

为了能够访问您的编辑器工具包,您应该保留对它的引用。事实上,你的 setEditor() 方法的名称是 setXXX 所以这应该是一个 setter (事实上,我不相信你需要多次设置它,所以它可能是这种方法根本不应该存在)。定义一个字段:

private RTFEditorKit kit = new RTFEditorKit();

然后在构造函数中,

setEditorKit( kit );
kit.read(...);

如果你坚持保留该方法,它的代码应该是

kit = new RTFEditorKit();
setEditorKit( kit );

如果您从构造函数中使用它,请记住最初将 kit 设置为 void,以免创建一个将立即被丢弃的额外对象。

我一直在寻找用于将 RTF 文档加载到 JTextPane 中的 java 实现。除了这个线程,我找不到其他任何东西。因此,我将 post 在此列出我的解决方案,以防对其他开发人员有所帮助:

            private static final RTFEditorKit RTF_KIT = new RTFEditorKit();
            (...)
            _txtHelp.setContentType("text/rtf");
            final InputStream inputStream = new FileInputStream(_helpFile);
            final DefaultStyledDocument styledDocument = new DefaultStyledDocument(new StyleContext());
            RTF_KIT.read(inputStream, styledDocument, 0);
            _txtHelp.setDocument(styledDocument);