JLabel ImageIcon的类路径资源

问题描述 投票:0回答:1

我想在JLabel中添加一个图像,该图像也可以在Eclipse中构建项目后显示。

我有此代码。.

 jLabel1.setIcon(new ImageIcon(getClass().getResource("/student/information/system/images/bk4.jpg")));
java swing jlabel embedded-resource
1个回答
0
投票

天哪,为什么要尝试一行读取图像文件?

首先,请确保为您的项目定义了资源文件夹,并且该资源文件夹在构建路径上。

这是我的一个Java项目中的示例。

Build Path

接下来,编写一种从资源文件夹读取图像文件的方法。

private Image getImage(String filename) {
    try {
        return ImageIO.read(getClass().getResourceAsStream(
                "/" + filename));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

读取图像文件一次,将结果保存在类变量ImageIcon中。

imageIcon = getImage("image.png");

最后,在您的Swing代码中引用ImageIcon。

jLabel1.setIcon(imageIcon);
© www.soinside.com 2019 - 2024. All rights reserved.