1

I've got a window (public class Panel extends JPanel) that is setting its background from URL

@Override
protected void paintComponent(Graphics g)
{
    super.paintComponent(g);
    try
    {
        this.imgBG = ImageIO.read(new URL("http://myhost.com/bg.png"));
    }
    catch (Exception e)
    {
        System.out.println("[ERROR] Could not load custom background image! Using resources.");
        this.imgBG = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/bg.png"));
    }
    g.drawImage(imgBG, 0, 0, this);
}

If it won't load an image, then it will use one from Resources. The problem is those images are heavy in memory and loading them is lagging whole window. Is there a way I can paint BG in background thread? If not, is this a good solution:

  1. Use LayeredPanel
  2. Create JLabel with size of window and place it in background
  3. Make new Runnable thread that will get image and JLabel.setIcon(image)
Ernio
  • 948
  • 10
  • 25
  • 1
    I think you'll have serious *lag* or performance issues, if you're loading the image everytime `paintComponent` is called. *Especially* if the image is loaded from the network. Painting from a background thread isn't a good idea, in general. You should leave painting to the Event-Dispatch Thread, unless you're trying to do *active rendering*. In any case, load the images prior to do any painting, if possible. – afsantos Feb 25 '14 at 17:30
  • Use `SwingWorker`, seen [here](http://stackoverflow.com/q/4530428/230513). – trashgod Feb 25 '14 at 17:34

1 Answers1

0

Generally, you should never load resources with in any paint method. Paint methods will be called multiple times during the life cycles of your application.

Try using a SwingWorker to load the image in the background and update the panel when it's done

You could load the images at the start of the program as part of the programs loading process, for example....

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • This URL image is being constantly changed by a php script on the web. My app had to update it every few seconds. I managed to do this via SwingWorker, thanks. – Ernio Feb 26 '14 at 15:10