简体   繁体   中英

No image showing on JFrame when adding image to label

I have written some lines of code that supposed to show the image as a label in the JFrame. Here is the code.

ImageIcon image = new ImageIcon("funny.jpg");

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

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
frame.add(label);

As you were prompted in the comments of your question, I think you should take care of ensuring that the file exists in the specified location, and using getResource for example.

Other than that, you are not utilizing the image's observer pattern for the JLabel . Try setting the ImageObserver of the image to label , like so:

ImageIcon image = new ImageIcon("funny.jpg");

JLabel label = new JLabel();
label.setIcon(image);
image.setImageObserver(label); // <-- Added this line.

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
frame.add(label);

Else, see the corresponding documentation on setImageObserver .

You can also check the corresponding tutorials' section .

That happens to be because, as far as I know, ImageIcon uses a MediaTracker to load the image asynchronously, so when you construct an instance of an ImageIcon it will return without first blocking until the image is fully loaded. Setting the ImageObserver of the ImageIcon will ensure that the ImageObserver you supplied will get notified about the state of loading the image when the state changes. The default implementation of Component (which is an ImageObserver ) repaints itself so you will then be able to see the image fully loaded, when it is ready.

As an alternative, you can always use ImageIO#read which will block until the image is fully loaded into memory (but it will only return a single frame in an animated GIF image for example).

I did not test it though, but that's a problem I encouter very often so I think it should work. If it did or it didn't, let me know.

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