I have coded the following code:
JDialog helpDialog = new JDialog();
helpDialog.setTitle("Help");
helpDialog.setResizable(false);
helpDialog.setAlwaysOnTop(true);
helpDialog.setSize(393, 43);
help.setSize(195,195);
help.setEditable(false);
help.setFont(new Font("Arial", Font.PLAIN, 24));
String txt = "<b><big>"+ "Help Page " +"</big></b>" + "<br/>" +
" <img src= \" ..\\image.jpg \" alt= \" Logo \" height= \" \" width=\" 42 \"> ";
help.setContentType("text/html");
help.setText(txt);
help.setCaretPosition(0);
helpDialog.add(help);
helpDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
helpDialog.pack();
helpDialog.setVisible(true);
//Window in center of the display not in the left top corner
helpDialog.setLocationRelativeTo(null);
This dialog is just to inform the user. I want to add an image via String txt = "<b><big>"+ "Help Page " +"</big></b>" + "<br/>" +
" <img src= \" ..\\image.jpg \" alt= \" Logo \" height= \" \" width=\" 42 \"> ";
, however the image does not get displayed even though its in the scr
folder.
Any recommendations where to put it?
I appreciate your answer!
Try something more like...
<img src='" + getClass().getResource("/path/to/image/image.jpg").toString() + "' .../>
instead...
Two main reasons your code isn't working...
src
directory won't exist when the application is built and the image will be included in the resulting Jar file (assuming you're using something like Netbeans or are building it by hand, otherwise, Eclipse will require the image file to be put in the resources
directory instead). This means that the resource can no longer be referenced as a file in the normal manner you are probably use to and .....\\image.jpg
is not a valid URL for the API to resolve to the image (basically, it won't know how to find it), apart from anything else, the relative context is, well, contextual and could change...For example
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ShowMeTheImage {
public static void main(String[] args) {
new ShowMeTheImage();
}
public ShowMeTheImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
String text = "<html><img src='" + getClass().getResource("/images/battle.jpg").toString() + "'/>";
JOptionPane.showMessageDialog(null, text);
}
});
}
}