Reputation: 3
I need image icon on jframe but I dont want to give path. I am using this
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\ABC\\Desktop\\folder name\\1.jpg"));
Because every system has different path and this is the reason I can not compile this on other system(computer).
I need some way so I can set image icon through file name only. And the image is in src
folder.
Upvotes: 0
Views: 2525
Reputation: 159754
Read the Image
as an embedded resource. The new images
folder shown here just needs to be available on the classpath
public class ImageApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Image image = null;
try {
image = ImageIO.read(getClass().getResource("/images/1.png"));
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Image App");
frame.add(new JLabel(new ImageIcon(image)));
frame.pack();
frame.setVisible(true);
}
});
}
}
Upvotes: 4
Reputation: 320
You can use relative path: for example, if icon is in program working directory (the same directory as program) you can just use "1.jpg", if in folder - "folderName/1.jpg".
Upvotes: -1