Java Swing: unable to load image using getResource

蓝咒 提交于 2019-11-29 16:22:38
patrick

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

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.

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