Relative path in JLabel HTML

I am trying to make JLabel show an html that refers to an image using a relative path. But I can not get JLabel to find the image. It works great when I use the absolute path.

I tried to run the program from the command line or from eclipse and add a dialog to show me where the current working directory is, but for avail. I came to the conclusion that the image is not visible in the current directory, which brings me to the point. where to look for the image?

here is the test code that shows what i am doing:

import javax.swing.*;

public class HTMLLabel extends JFrame {
    public HTMLLabel() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JOptionPane.showMessageDialog( this, 
                System.getProperty("user.dir"));

         String html = "<html>\n" +
        "   <body>\n" +
        "       <div style=\"text-align: center;\">\n" + 
        "           <img src=\"file://s.png\">\n"+
        "       </div>\n"+
        "   </body>\n"+
        "</html>";

         JLabel label = new JLabel(html);
         add(label);

         pack();
         setVisible(true);
    } 

    public static void main(String[] args) {
         new HTMLLabel();
    }
}
+5
source share
4 answers

html- JLabel .

public static String prepareHtmlToJLabelText(Class relativeClass, String html) {
    Pattern p = Pattern.compile("src=['\"](.*?)['\"]");
    Matcher m = p.matcher(html);
    while (m.find()) {
        html = html.replace(m.group(), "src='" + relativeClass.getResource(m.group(1)) + "'");
    }
    return html;
}

"src", .

:

jLabel.setText(prepareHtmlToJLabelText(this.getClass(), "<html><div style='text-align: center;'><img src='imageA.png'></div>Bla bla bla...<div style='text-align: center;'><img src='imageB.png'></div>"));

html JEditorPane.

+3

:

, ,

"                       <img src=\"file:s.png\">\n"+

, s.png .

, , :

URL url = HTMLLabel.class.getResource( "/s.png" );
  String html = "<html>\n" +
    "       <body>\n" +
    "               <div style=\"text-align: center;\">\n" + 
    "                       <img src=\""+url+"\">\n"+
    "               </div>\n"+
    "       </body>\n"+
    "</html>";
+3

? JLabel(Icon image)

JLabel label = new JLabel(createImageIcon("s.png","description"));

protected ImageIcon createImageIcon(String path, String description) {
  java.net.URL imgURL = getClass().getResource(path);
  if (imgURL != null) {
    return new ImageIcon(imgURL, description);
  } else {
    System.err.println("Couldn't find file: " + path);
    return null;
  }
}

, html-.

btw 3 (file://s.png ), file:///s.png C:\s.png. , .

String path = System.getProperty("user.dir");
String html =
  "<html>\n" +
     "<body>\n" +
        "<div style=\"text-align: center;\">\n" +
          "<img src=\"file:///"+path+"/s.png\">\n"+
        "</div>\n"+
     "</body>\n"+
  "</html>";

.

+2

<img src=\"file://s.png\">\n"
//with
<img src=\"file:///s.png\">\n"+

. s.png src/java

0

All Articles