JLabel ImageIcon的类路径资源 [英] Class path resource for JLabel ImageIcon

查看:151
本文介绍了JLabel ImageIcon的类路径资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我有这段代码。 /images/bk4.jpg))));


解决方案

天哪,为什么要读取图像文件



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



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





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

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

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

  imageIcon = new ImageIcon(getImage( image .png)); 

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

  jLabel1.setIcon(imageIcon); 


I want to add a image in JLabel that can display after building the project too in eclipse.

I have this code..

 jLabel1.setIcon(new ImageIcon(getClass().getResource("/student/information/system/images/bk4.jpg")));

解决方案

Goodness, why are you trying to read an image file in one line?

First, make sure that your resources folder is defined for your project and is on the build path.

Here's an example from one of my Java projects.

Next, code a method to read image files from the resources folder.

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

Read the image file once, saving the result in a class variable ImageIcon.

imageIcon = new ImageIcon(getImage("image.png"));

Finally, reference the ImageIcon in your Swing code.

jLabel1.setIcon(imageIcon);

这篇关于JLabel ImageIcon的类路径资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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