Search code examples
javaswingjlabelembedded-resourcegetresource

Java Swing: unable to load image using getResource


I'm trying to isolate where the problem could be when trying to add an image to the class directory. (Doing this so when I export as a runnable JAR, the image is included in the package).

So I've got the strawberry.jpg file sitting in 'C:\Users\sean\workspace\myApps\src\testing' Could you advise what I'm missing? Thanks!

package testing;

import java.awt.*;
import javax.swing.*;

public class IconTest {

    public static void main(String[] arguments) {

        JFrame frame1 = new JFrame();
        frame1.setTitle("Frame1");
        frame1.setSize(500, 500);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flo = new FlowLayout();
        frame1.setLayout(flo);

        JLabel label1 = new JLabel(new ImageIcon(
            IconTest.class.getResource("strawberry.jpg")));
        frame1.add(label1);
        frame1.setVisible(true);
    }
}

Solution

  • I would use SomeClass.class.getResourceAsStream("...") as in the following example:

    public static void main(String[] arguments) throws IOException {
    
        JFrame frame1 = new JFrame();
        frame1.setTitle("Frame1");
        frame1.setSize(500, 500);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flo = new FlowLayout();
        frame1.setLayout(flo);
    
        InputStream resourceAsStream = IconTest.class.getResourceAsStream("strawberry.jpg");
        Image image = ImageIO.read(resourceAsStream);
    
        JLabel label1 = new JLabel(new ImageIcon(image));
        frame1.add(label1);
        frame1.setVisible(true);
    }