简体   繁体   English

强制JLabel在昂贵的操作之前显示文本

[英]Forcing JLabel to display text before expensive operation

I'm having trouble getting a JLabel to display text immediately before updating it with an ImageIcon . 在使用ImageIcon更新JLabel之前,我无法立即显示文本。

I have a JLabel that is a fixed size that will be displaying either text or an image that fits it perfectly. 我有一个固定大小的JLabel,它将显示文本或完全适合它的图像。 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. 我试图让它显示文本“正在加载...”,然后立即将其从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);
}

...

(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? 如何强制摆动以更新JLabel,然后再将其替换为图像? 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 ;) 看看SwingWorker并在这里阅读GUI / Threads / Background Threads(不仅是我链接的第一页,还有下面的那些) Event Dispatch Thread ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM