JEditorPane Document length return always 0

40 Views Asked by At

I'm using a JEditorPane document to be filled from a String. I execute the following code, but I do not understand why the following instruction returns always 0 for the document length.

Thank you in advance for your detailed explanations.

    String xxx  = "This is my text sample";
    
    
    javax.swing.JEditorPane p = new javax.swing.JEditorPane();
    p.setContentType("text/rtf");
    EditorKit kitRtf = p.getEditorKitForContentType("text/rtf");
    java.io.InputStream stream = new java.io.ByteArrayInputStream(xxx.getBytes()); 
    kitRtf.read(stream, p.getDocument(), 0);
    System.out.println(p.getDocument().getLength());
1

There are 1 best solutions below

0
hfontanez On

The reason why your code outputs zero is because your editor kit, the string, and the document in the editor pane are disjointed. There are no relationship between them, especially between the editor kit and the document. Look at a simple example without an editor kit first. It will show the relationship between the string you want to set and the document. The process is simple:

  1. Create the document
  2. Set the document in the editor pane
  3. Insert the string into the document (this example inserts the string at index 0)

Without Editor Kit

public static void main(String[] args) throws IOException, BadLocationException {
    String xxx  = "This is my text sample";
    javax.swing.JEditorPane p = new javax.swing.JEditorPane();
    Document doc = new DefaultStyledDocument();
    p.setDocument(doc);
    doc.insertString(0, xxx, null);
    System.out.println(p.getDocument().getLength());
}

This outputs 22.

Now that you know how to connect the string to the document, let's add the editor kit. When using an editor kit, you got to make sure there is a relationship or association between the document and the editor kit. For this:

  1. Create the editor kit
  2. Use the editor kit to create the document you want to use. Since you wanted RTF, I created an RTF Editor, but for this issue, this is not relevant. You could create any type of editor kit.
  3. Insert the String into the document and set the document into the editor pane.

With Editor Kit

public static void main(String[] args) throws IOException, BadLocationException {
    String xxx  = "This is my text sample";
    javax.swing.JEditorPane p = new javax.swing.JEditorPane();
    EditorKit kitRtf = new RTFEditorKit();
    Document doc = kitRtf.createDefaultDocument();
    p.setDocument(doc);
    doc.insertString(0, xxx, null);
    System.out.println(p.getDocument().getLength());
}

This also outputs 22