强制JLabel在昂贵的操作之前显示文本 [英] Forcing JLabel to display text before expensive operation

查看:53
本文介绍了强制JLabel在昂贵的操作之前显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 ImageIcon 更新文本之前,我很难获得 JLabel 来显示文本.

I'm having trouble getting a JLabel to display text immediately before updating it with an ImageIcon.

我有一个固定大小的JLabel,它将显示完全适合它的文本或图像.我试图让它显示文本正在加载...",然后立即从URL加载图像并用它替换文本.

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.)

上面的代码不显示文本;发生的所有事情都是应用程序在图像下载和显示后挂起一秒钟,通常是按预期的那样挂起.在继续将其替换为图像之前,如何强制Swing更新JLabel?或者,您知道实现这一目标的另一种更有效的方法吗?

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?

推荐答案

看看

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 ;)

这篇关于强制JLabel在昂贵的操作之前显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆