Java 将RTF加载到JTextPane中
我在文本编辑器程序中创建了一个JTextPane类型的类。它有一个子类text和richtext,它来自我的主JTextPaneClass。但是,我无法将RTF加载到richtext中,因为读取fileinput流的方法不在超类JTextPane中。那么如何将富文本读入jtextpane呢?这似乎很简单,我一定是遗漏了什么。我看到很多使用RTFEditorKit并填充到JTextPane中的示例,但在将其实例化为类时却没有Java 将RTF加载到JTextPane中,java,rtf,jtextpane,fileinputstream,Java,Rtf,Jtextpane,Fileinputstream,我在文本编辑器程序中创建了一个JTextPane类型的类。它有一个子类text和richtext,它来自我的主JTextPaneClass。但是,我无法将RTF加载到richtext中,因为读取fileinput流的方法不在超类JTextPane中。那么如何将富文本读入jtextpane呢?这似乎很简单,我一定是遗漏了什么。我看到很多使用RTFEditorKit并填充到JTextPane中的示例,但在将其实例化为类时却没有 public class RichTextEditor extends
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);
告诉我
类型JEditorPane中读取的方法(InputStream,Document)不适用于参数(FileInputStream,Document,int)
为了能够访问编辑器工具包,您应该保留对它的引用。事实上,您的
setEditor()
方法的名称是setXXX
,因此这应该是一个setter(事实上,我不认为您需要多次设置它,因此可能根本不存在此方法)。定义一个字段:
private RTFEditorKit kit = new RTFEditorKit();
然后在构造函数中
setEditorKit( kit );
kit.read(...);
如果您坚持保留该方法,则其代码应为
kit = new RTFEditorKit();
setEditorKit( kit );
如果您从构造函数中使用它,记得在开始时将
kit
设置为void
,这样就不会创建一个会立即被丢弃的额外对象。我一直在寻找一个java实现,用于将RTF文档加载到JTextPane中。除了这根线,我找不到别的东西了。因此,我将在这里发布我的解决方案,以防这对其他开发人员有所帮助:
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);
这个
0
有什么作用?在文档中定位放置内容的位置。但是你从哪里得到读取的定义?这肯定不是绝地武士传来的。而你还没有超越它。为什么您认为它应该有一个名为read()
的三个参数的方法?它来自javax.swing.text.rtf.RTFEditorKit.read
对。。。因此,您不能期望this.read()
了解它,因为它不扩展RTFEditorKit
。基本上,您应该设置编辑器工具包,并使用编辑器工具包对象的读取
,如果这是您想要的。