如何使用SwingWorker下载和显示图像

时间:2019-03-24 17:45:08

标签: java swing swingworker

我用Java编写了一个程序,该程序使用JSoup从Internet下载图像(给定了链接),并在按gui中的按钮时将其保存到计算机的特定文件夹中。请注意,URL输入不一定是图像本身的URL,而是包含图像的HTML网页的URL。我接下来要做的是在屏幕上显示该图像。问题是,我不能简单地抢先创建ImageIcon对象,因为在编译时系统中还没有该图像文件。

面板类

public class AdditionPanel extends JPanel
{

    // ...
    static JTextPane textpane;
    JLabel paneInstructions;
    JButton linkOk;

    public AdditionPanel() throws IOException
    {

        textpane = new JTextPane();         
        paneInstructions = new JLabel("Paste the link here:");
        linkOk = new JButton(" OK ");

        // ...

        linkOk.addActionListener(new LinkOkPressed());

        // ...

        this.add(textpane);
        this.add(paneInstructions);
        this.add(linkOk);
    }
}

动作监听器

public class LinkOkPressed implements ActionListener
{
    JLabel test;
    @Override
    public void actionPerformed(ActionEvent e)
    {
        // ImageDownloader is a class I have created, that simply saves the image
        // from the given URL in a predetermined directory
        ImageDownloader.saveImage(ImageDownloader.getImageUrl(AdditionPanel.textpane.getText()));
        ImageIcon poster = new ImageIcon(getClass().getResource("/resources/imgtest.jpg"));
        test= new JLabel(poster);
        AdditionPanel.add(test);
    } 
}

因此,现在我尝试使用SwingWorker尝试仅在按下按钮后才访问文件,从而下载了文件。这是我到目前为止的内容:

SwingWorker类

public class SaveAndDisplay extends javax.swing.SwingWorker<Void, Void>
{

    private AdditionPanel additionPanel;

    public SaveAndDisplay(AdditionPanel addPanel)
    {
        additionPanel = addPanel;
    }

    @Override
    protected Void doInBackground() throws Exception
    {
        ImageDownloader.saveImage(ImageDownloader.getImageUrl(AdditionPanel.textpane.getText()));
        // Wait until the image is saved.

        return null;
    }

    @Override
    protected void done()
    {
        // The following line causes a "NullPointerException"           
        javax.swing.ImageIcon poster = new javax.swing.ImageIcon(LinkOkPressed.class.getResource("/resources/imgtest.jpg"));
        javax.swing.JLabel test= new javax.swing.JLabel(poster);
        test.setBounds(270, 70, 300, 250);
        additionPanel.add(test);
    }
}

上面的类在执行时导致异常。不幸的是,我对SwingWorker不太熟悉,并且在这里停留了一段时间。任何帮助将不胜感激。

0 个答案:

没有答案