Search code examples
javaswingjtextpane

JTextPane replace string in document


I had JTextPane with content type HTML

JTextPane editor = new JTextPane();
editor.setContentType("text/html");

When user input "\" I want to be inputted "&#92" (code of "\"). How can I do it?


Solution

  • When user input "\" I want to be inputted "&#92" (code of "\"). How can I do it?

    Use a DocumentFilter to translate the string before it is entered into the Document.

    Read the section from the Swing tutorial on How to Implement a DocumentFilter for more information to get you started.

    To override the replace(...) method you might do something like:

    public void replace(final FilterBypass fb, final int offs, final int length, final String str, final AttributeSet a)
    {
        if (str.equals("\"))
            super.replace(fb, ofs, length, "&#92", a);
        else
            super.replace(fb, offs, length, str, a);
    }