I'm trying to use this code, but it will only display the image in jtextpane and it does not display the text.

JLabel label = new JLabel("<html>some text here<img src='http://www.yoursie.com/image.jpg'></html>");

then using this label in JTextPane.

Edited 1 Year Ago by peter_budo: Code formatting

  • good catch by @JamesCherrill "use this JLabel in a JTextPane"?,

  • use JEditorPane, without using JLabel as container for image (is possible but there couldn't be real reason for ...),

  • or JLabel (without parent from JTextComponents) is correct way to do that too

I figured it out, the height in setPreferredSize(new Dimension(2500, 100) was to small.

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class jtextpane extends JTextPane 

  public jtextpane()
    setPreferredSize(new Dimension(750, 200));  

    StyledDocument doc = getStyledDocument();
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);

    String str = "<html><b>hello</b><img src='http://www.bigcats.com/clouded-leopard-900x165'></html>";
    JLabel msgJL = new JLabel();

    JPanel panel = new JPanel();
    panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.X_AXIS));
    panel.setPreferredSize(new Dimension(2500, 100));
    panel.setMaximumSize(new Dimension(2500, 100));

    Style s = doc.addStyle("label", regular);
    StyleConstants.setComponent(s, panel);  

    try { doc.insertString(doc.getLength(), "label", doc.getStyle("label")); }
    catch (BadLocationException ble) { System.err.println("Couldn't insert initial text into text pane."); }
    public static void main(String[] args)  
      JFrame frame = new JFrame();
      frame.add(new jtextpane());

Thank you,

This question has already been answered. Start a new discussion instead.