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.

What code are you using to "use this JLabel in a JTextPane"?

  • 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));  
    setEditable(true);

    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));
    panel.add(msgJL);
    msgJL.setText(str);

    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());
      frame.pack();
      frame.setVisible(true);
      }
  }

Thank you,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.