强制 JLabel 在昂贵的操作之前显示文本
我无法让 JLabel
在使用 ImageIcon
更新它之前立即显示文本。
我有一个固定大小的 JLabel,它将显示完全适合它的文本或图像。我试图让它显示文本“正在加载...”,然后立即让它从 URL 加载图像并用它替换文本。
...
public void setImage()
{
URL url = new URL("http://www.website.com/pathtoimage/image.png");
jLabel1.setIcon(null);
jLabel1.setText("Loading...");
ImageIcon ii = new ImageIcon(url);
jLabel1.setIcon(ii);
}
...
(假设异常被正确捕获并且所有必需的导入都已完成,并且图像存在并且有效。)
上面的代码不显示文本;所发生的只是应用程序在下载图像并在几分之一秒后显示时挂起,这基本上符合预期。在继续用图像替换 JLabel 之前,如何强制 swing 更新 JLabel?或者,您知道一种不同的、更有效的方法来实现这一目标吗?
I'm having trouble getting a JLabel
to display text immediately before updating it with an ImageIcon
.
I have a JLabel that is a fixed size that will be displaying either text or an image that fits it perfectly. I'm trying to get it to display the text "Loading..." and then immediately after, get it to load an image from a URL and replace the text with it.
...
public void setImage()
{
URL url = new URL("http://www.website.com/pathtoimage/image.png");
jLabel1.setIcon(null);
jLabel1.setText("Loading...");
ImageIcon ii = new ImageIcon(url);
jLabel1.setIcon(ii);
}
...
(Assume that exceptions are caught properly and all required imports are made, and that the image exists and is valid.)
The above code does not display the text; all that happens is the application hangs as the image is downloaded and displayed after a fraction of a second, mostly as expected. How can I force swing to update the JLabel before progressing on to replace it with the image? Or, do you know a different, more efficient way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看 SwingWorker 并在此处阅读有关 GUI/线程/后台线程的信息(不仅是我链接的第一页,还包括以下页面)事件调度线程 ;)
Have a look at SwingWorker and read about GUI/Threads/Background Threads here (not only the first page I linked but also the ones following) Event Dispatch Thread ;)