Question

I have been using a JTextPane to display basic HTML content including locally saved images. I have been trying to style the JTextPane using the text pane's input attributes. Whenever I modify the styling of the pane, the HTML images I have break and won't appear without commenting out the styling code.

This is an SSCE of the code:

import java.awt.Color;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class JTextPaneImageTest {

    public static void main(String[] args) {
        new JTextPaneImageTest();
    }

    public JTextPaneImageTest() {
        JTextPane textPane = new JTextPane();
        textPane.setContentType("text/html");
        textPane.setEditable(false);

        String content = "<html><body><p>Test text here</p>"
                + "<img src=\"file:\\\\\\C:\\Users\\racha_000\\AppData\\Local\\Temp\\ebookr\\test.jpg\" />"
                + "</body></html>";
        System.out.println(content);

        HTMLEditorKit editorKit = (HTMLEditorKit) textPane.getEditorKit();
        HTMLDocument htmlDoc = (HTMLDocument) textPane.getDocument();
        MutableAttributeSet mats = textPane.getInputAttributes();
        StyleConstants.setForeground(mats, Color.RED);

        try {
            editorKit.insertHTML(htmlDoc, htmlDoc.getLength(), content, 0, 0, null);
        } catch (BadLocationException | IOException e) {
            e.printStackTrace();
        } finally {
            htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, true);
        }

        JFrame frame = new JFrame();
        frame.add(textPane);
        frame.setVisible(true);
    }
}

The important code to note is that whenever the mutable attribute set is changed and the character attributes set, the images don't work.

MutableAttributeSet mats = textPane.getInputAttributes();
StyleConstants.setForeground(mats, Color.RED);
htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, true);

Without styling:

Without Styling

With styling:

With Styling

Styling the document this way has been the only method that has worked for me as I insert the content all at once as HTML and style it all the same way. Other methods haven't worked, so I'm hoping to be able to maintain this method of styling the panel.

Was it helpful?

Solution

Calling the setCharacterAttributes() method with its last argument (replace) to true somewhat erases HTML code related to your image.

Simply call it with false and it works:

htmlDoc.setCharacterAttributes(0, htmlDoc.getLength(), mats, false);

image displayed with styled text

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top