JTextPane appending a new string

后端 未结 3 932
难免孤独
难免孤独 2020-11-27 04:40

In an every article the answer to a question \"How to append a string to a JEditorPane?\" is something like

jep.setText(jep.getText + \"new string\");
         


        
3条回答
  •  [愿得一人]
    2020-11-27 05:16

    A JEditorPane, just a like a JTextPane has a Document that you can use for inserting strings.

    What you'll want to do to append text into a JEditorPane is this snippet:

    JEditorPane pane = new JEditorPane();
    /* ... Other stuff ... */
    public void append(String s) {
       try {
          Document doc = pane.getDocument();
          doc.insertString(doc.getLength(), s, null);
       } catch(BadLocationException exc) {
          exc.printStackTrace();
       }
    }
    

    I tested this and it worked fine for me. The doc.getLength() is where you want to insert the string, obviously with this line you would be adding it to the end of the text.

提交回复
热议问题