Home > Net >  jtextpane html image doesnt load
jtextpane html image doesnt load

Time:11-19

I wanted to create a scrollable jtextpane with some html text. Inside, there are some image elements. If I open the file with a browser the image show up correctly and everything is fine.

My problem is that I cant just simply modify the text with some java code because its located inside a properties file, so Im kind of forced to get the right location path.

Does someone know a trick to still use the html text with an properties file with working images?

text=<html>
  <head></head>
  <body>
     <h3>Seer:</h3>
     <img src="icons/roles/seer_icon.png" align="left" height="64"/>
  </body>
</html>

CodePudding user response:

Because src="icons/roles/seer_icon.png" does not start with http: or https:, it is a relative URL. A relative URL’s true location depends on the URL which acts as the base context for the HTML document.

If you load HTML content from a URL using setPage, the base is that URL. But if you load from a String, as you’re probably doing since you are getting the content from a properties file, there is no base URL. Which means src="icons/roles/seer_icon.png" makes no sense—there is no base to resolve it against.

But you can specify the base yourself:

HTMLDocument doc = (HTMLDocument) textPane.getStyledDocument();
doc.setBase(MyApplication.class.getResource("/"));

Note that HTML may not be the best way to show content, unless you need to give the user the ability to copy and paste it. You can always create the content yourself:

// Properties file contains:
// text=Seer:
// icon=/icons/roles/seer_icon.png

String headingText = properties.getProperty("text");
String iconPath = properties.getProperty("icon");

JLabel headingLabel = new JLabel(headingText);
Font font = headingLabel.getFont();
font = font.deriveFont(24f);
headingLabel.setFont(font);

headingLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 12, 0));

Icon icon = new ImageIcon(MyApplication.class.getResource(iconPath));
JLabel iconLabel = new JLabel(icon);

JPanel content = new JPanel(new BorderLayout());
content.add(headingLabel, BorderLayout.PAGE_START);
content.add(iconLabel, BorderLayout.CENTER);
  • Related