简体   繁体   中英

Image doesn't appear in the JFrame

import javax.swing.*;
public class GUI {
    public static void main(String s[]) {
        ImageIcon image = new ImageIcon("logo.png");

        JFrame frame = new JFrame();
        JLabel label = new JLabel();
        label.setIcon(image);

        label.setText("Boom");
        frame.setTitle("SJ");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.add(label);
    }  
}

I am beginner and just learning JFrame , can you guys tell me why isn't the image showing up? I have placed the Image (logo.png) in the folder where is that class. I am using VSCode as IDE. Thanks in advance!!

Dusted off the old NetBeans and gave it a go...

You would want to do this:

ImageIO.read(getClass().getResource("logo.png"))

Essentially the image is bundled in your jar file as a resource and in order to correctly extract it you need the Class#getResource(string name)

Here is my full example with screenshot of my image placement:

在此处输入图像描述

TestApp.java:

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TestApp {

    public TestApp() {
        initComponents();
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestApp();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        BufferedImage img = null;
        try {
            img =  ImageIO.read(getClass().getResource("logo.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        JLabel label = new JLabel(new ImageIcon(img));
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
    }
   
}

Which produces:

在此处输入图像描述

If your logo is perhaps inside nested java package like this:

在此处输入图像描述

You would simply do:

ImageIO.read(getClass().getResource("images/logo.png"))

Update:

As @camickr mentioned add all components to the JFrame before making it visible.

Also all Swing components should be created on the EDT via SwingUtilities.invokeLater as also shown in my example.

Thanks a Lot everyone whoever tried to help me!!

I used:

java.net.URL imageURL = app.class.getResource("download.png");
    ImageIcon img = new ImageIcon(imageURL);

It worked!! I referred it Here !

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