javaswingjeditorpanedomhtmleditorkit

JEditorPane HTMLDocument adds p-implied into HTML unnecessarily when setCharacterAttributes called


I am creating an editor using JEditorPane, HTMLDocument and HTMLEditorKit. I have a toolbar which has various components to change style attributes of the editor. One of them is a JComboBox to change the ZOOM_FACTOR attribute. The code below is the code that executes when that JComboBox 's value changes.

    final SimpleAttributeSet attrs = new SimpleAttributeSet();
    zoomCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String s = (String) zoomCombo.getSelectedItem();
            s = s.substring(1, s.length());
            double scale = new Double(s).doubleValue() / 100;
            editorPane.getDocument().putProperty("ZOOM_FACTOR", new Double(scale));

            try {
                StyledDocument doc = (StyledDocument) editorPane.getDocument();
                doc.setCharacterAttributes(0, 1, attrs, true);
                doc.insertString(0, "", null); // refresh
            } catch (Exception ex) {
                logger.error("Hata", ex);
            }
        }
    });

doc.setCharacterAttributes(0, 1, attrs, true); is the line where root of my problem starts. After this line of code executes, <p-implied> is added into the <head></head> part of the HTML text in the JEditorPane.getText. And after this happens, if some certain pattern of events occur my HTML text gets corrupted. Is there any way how not to create <p-implied> along? If not so what could be the best workaround for this problem?

PS : There is something old reported here in the JDK Bug System. It is reported for a different reason, but it is shown there also, that the same <p-implied> is being added into <head></head> afterwards. I know the problem reported in this link uses JTextPane (a subclass of JEditorPane) and setCharacterAttributes method in the JTextPane class but that method also calls same setCharacterAttributes method I used inside itself.


Solution

  • You use 0 position, but for HTMLDocument the positions belong to HEAD (not BODY) section.

    Looks like you use it just to refresh the content. You can apply the same code for the end of the document.

    doc.setCharacterAttributes(doc.getLength(), 1, attrs, true);
    

    Thus the attribute change event is applied to the BODY.