Caminho relativo em Jlabel Html
-
22-09-2019 - |
Pergunta
Estou tentando fazer Jlabel mostrar um HTML que está referenciando uma imagem usando um caminho relativo. Mas não posso fazer Jlabel localizar a imagem. Funciona bem quando estou usando o caminho absoluto.
Eu tentei executar o programa na linha de comando ou no eclipse e adicionar diálogo para me mostrar onde está o diretório de trabalho atual, mas para aproveitar. Portanto, cheguei à conclusão de que a imagem não é pesquisada no diretório atual - o que me leva ao ponto. Onde a imagem é procurada?
Aqui está um código de teste que mostra o que estou fazendo:
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();
}
}
Solução
Use esta função para preparar o texto HTML para o jlabel exibir imagens em relação ao pacote de uma classe.
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;
}
A função substitui o conteúdo do atributo "SRC" para torná -lo em relação à classe do provedor.
Exemplo:
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>"));
De qualquer forma, para um suporte real de HTML, use Jeditorpane.
Outras dicas
Eu vejo duas variantes:
Eu não sei por que, mas para mim isso funciona
" <img src=\"file:s.png\">\n"+
Supondo que o s.png esteja no diretório de trabalho atual.
Outra variante que parece mais apropriada para mim é:
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>";
Por que você está fazendo assim? Basta usar isso JLabel(Icon image)
construtor
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;
}
}
Ou se você insistir na variante HTML.
btw o protocolo de arquivo usa 3 barras (file://s.png
é inválido) e file:///s.png
significaria C:\s.png
. Se a imagem reside no diretório inicial que você poderá usar.
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>";
Mas não tenho garantias sobre a segunda solução.
Acabei de substituir o seu
<img src=\"file://s.png\">\n"
//with
<img src=\"file:///s.png\">\n"+
E isso resolveu o problema
Nota: Coloquei o arquivo s.png na pasta SRC/Java