[英]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.我已经编写了一些代码行,应该在 JFrame 中将图像显示为 label。 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.正如您在问题的评论中被提示的那样,我认为您应该注意确保文件存在于指定位置,例如使用
getResource
。
Other than that, you are not utilizing the image's observer pattern for the JLabel
.除此之外,您没有将图像的观察者模式用于
JLabel
。 Try setting the ImageObserver
of the image
to label
, like so:尝试将
image
的ImageObserver
设置为label
,如下所示:
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
.否则,请参阅
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.这恰好是因为,据我所知,
ImageIcon
使用MediaTracker
异步加载图像,因此当您构造ImageIcon
的实例时,它将返回而不会首先阻塞,直到图像完全加载。 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.设置
ImageIcon
的ImageObserver
将确保您提供的ImageObserver
将在 state 更改时收到有关加载图像的 state 的通知。 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. Component
(它是一个ImageObserver
)的默认实现会重新绘制自身,因此您将能够在图像准备好时看到完全加载的图像。
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).作为替代方案,您始终可以使用
ImageIO#read
它将阻塞直到图像完全加载到 memory (但它只会返回动画 GIF 图像中的单个帧)。
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.
如果有或没有,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.