是否有使用ImageIcon和URL下载图像的异步方式?

时间:2018-08-09 01:01:58

标签: java

从URL提取图像时,找不到在下载时显示加载图标的方法。这是我的方法:

    private void fetchAdImage(String clickedLink) {
        try {
            // This gets completely ignored \/
            adDisplayLabel.setIcon(new ImageIcon(MainFrame.class.getResource("/icons/spinner.png")));
            // /\
            URL link = new URL(clickedLink);
            ImageIcon adImage = new ImageIcon(link, "");
            int difference;
            if (adImage.getIconHeight() > adDisplayLabel.getHeight()) {
                difference = adImage.getIconHeight() + adDisplayLabel.getHeight();
            } else {
                difference = adImage.getIconHeight() - adDisplayLabel.getHeight();
            }
            adDisplayLabel.setIcon(drawBorder(Tools.getResizedIcon(adImage, adImage.getIconWidth() - difference, adDisplayLabel.getHeight())));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

该想法是在“ onPreUpdate”阶段将JLabel的图标更改为“旋转”图像,并在“ onSuccess”阶段将其更改为下载的图像。问题是:这种下载方法没有这样的东西,先前的语句被完全忽略了。有使用Java下载图片的异步方式吗?

1 个答案:

答案 0 :(得分:1)

由于@Slaw的建议,我设法解决了这个问题(将代码包装在SwingWorker中,这是我所不知道的类)。这是代码:

    private void fetchAdImage(String clickedLink) {
        try {
            SwingWorker<ImageIcon, Void> worker = new SwingWorker<ImageIcon, Void>() {
                ImageIcon adImage;
                int difference;

                @Override
                protected ImageIcon doInBackground() throws Exception {
                    adDisplayLabel.setIcon(new ImageIcon(MainFrame.class.getResource("/icons/spinner.png")));
                    URL link = new URL(clickedLink);
                    adImage = new ImageIcon(link, "");

                    if (adImage.getIconHeight() > adDisplayLabel.getHeight()) {
                        difference = adImage.getIconHeight() + adDisplayLabel.getHeight();
                    } else {
                        difference = adImage.getIconHeight() - adDisplayLabel.getHeight();
                    }
                    return adImage;
                }

                protected void done() {
                    adDisplayLabel.setIcon(drawBorder(Tools.getResizedIcon(adImage, adImage.getIconWidth() - difference, adDisplayLabel.getHeight())));
                }
            };
            worker.execute();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }