Java Swing: unable to load image using getResource

允我心安 提交于 2019-12-18 09:31:49

问题


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);
    }
}

回答1:


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);
}



回答2:


Put the image file in the directory where your compiled classes are located and change the path in yor code by adding "/" before the filename:

JLabel label1 = new JLabel(new ImageIcon(
        IconTest.class.getResource("/strawberry.jpg")));

Resources are searched for in the class path.



来源:https://stackoverflow.com/questions/22733881/java-swing-unable-to-load-image-using-getresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!