Java Swing:无法使用getResource加载图像 [英] Java Swing: unable to load image using getResource

查看:323
本文介绍了Java Swing:无法使用getResource加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将图像添加到类目录时,我试图找出问题所在。 (这样做当我导出为可运行的JAR时,图像包含在包中)。

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).

所以我得到了位于'C的strawberry.jpg文件:\ Users \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
谢谢!

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


推荐答案

我如下例所示:

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

这篇关于Java Swing:无法使用getResource加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆