I have made a program in Java, that uses JSoup to download an image from the internet, given a link, and saves it into a specific folder in my computer, upon the pressing of a button in the gui. Please note, the URL input is not necessarily the URL of the image itself, but of an HTML webpage containing the image. What I want to do next is to display that image on the screen. The problem is, I can't simply create an ImageIcon object preemptively, because the image file doesn't exist in the system yet in compile time.
Panel Class
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);
}
}
Action Listener
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);
}
}
So now I am trying to use SwingWorker to try to access the file only after the button has been pressed, and thus the file has been downloaded. This is what I have so far:
SwingWorker Class
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);
}
}
The class above causes an exception when executed. Unfortunately, I am not very familiar with SwingWorker, and I have been stuck here for a while. Any help will be appreciated.