简体   繁体   中英

Class path resource for JLabel 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM