/*
 * @(#)LazyImageIcon.java  1.0 January 12, 2007
 *
 * Copyright (c) 2007 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms. 
 */

package ch.randelshofer.gui;

import ch.randelshofer.quaqua.util.Images;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import javax.swing.*;

/**
 * LazyImageIcon.
 *
 * @author Werner Randelshofer
 * @version 1.0 January 12, 2007 Created.
 */
public class LazyImageIcon extends ImageIcon {
    private BufferedImage bufferedImage;
    private SwingWorker worker;
    private int width;
    private int height;
    
    /** Creates a new instance. */
    public LazyImageIcon(final Image image, int width, int height) {
        this.width = width;
        this.height = height;
        worker = new SwingWorker() {
            public Object construct() {
                return Images.toBufferedImage(image);
            }
        };
        worker.start();
    }
    public LazyImageIcon(final URL image, int width, int height) {
        this.width = width;
        this.height = height;
        worker = new SwingWorker() {
            public Object construct() {
                return  Images.toBufferedImage(Toolkit.getDefaultToolkit().createImage(image));
            }
        };
        worker.start();
    }
    
    public Image getImage() {
        if (bufferedImage == null) {
            bufferedImage = (BufferedImage) worker.getValue();
        }
        return bufferedImage;
    }
    
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.drawImage(getImage(), x, y, c);
    }
    
    public int getIconWidth() {
        return width;
    }
    
    public int getIconHeight() {
        return height;
    }
}
