Load Image into JLabel not working
eclipse, java, javax.imageio, jlabel, swing
Solution
Don't read from a file, read from the class path
image = ImageIO.read(getClass().getResource(path));
-or-
image = ImageIO.read(MyClass.class.getResource(path));
When you use a `File` object, you're telling the program to read from the file system, which will make your path invalid. The path you are using is correct though, when reading from the class path, as you should be doing.
See the wiki on embedded resource. Also see `getResource()`
UPDATE Test Run
package org.apache.openoffice.sidebar;
import javax.swing.*;
public class SomeClass {
public SomeClass() {
ImageIcon icon = new ImageIcon(
SomeClass.class.getResource("/images/sidebar-icon-48.png"));
JLabel label = new JLabel(icon);
JFrame frame = new JFrame("Test");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SomeClass();
}
});
}
}
Problem
I try to display an image using a `JLabel`. This is my project navigator: From `SettingsDialog.java` I want to display an image using following code: ``` String path = "/images/sidebar-icon-48.png"; File file = new File(path); Image image; try { image = ImageIO.read(file); JLabel label = new JLabel(new ImageIcon(image)); header.add(label); // header is a JPanel } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` The code throws an exception: Can't read input file! Is the path of the image is wrong?