import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;
import java.io.*;

/** An instance is a JPanel that contains one image. Since it is
    a JPanel, it can be placed in a GUI. The system calls its method
    repaint whenever it is necessary to redraw the image.
   */
public class ImagePanel extends JPanel {
    
    private Image image;        // the image on the JPanel
 
    /** Constructor: a panel for image im with
        preferred size the size of im. */
    public ImagePanel(Image im) {
        image= im; 
        if (im == null)
            return;
        int rows= im.getHeight(this);
        int cols= im.getWidth(this);
        Dimension dim= new Dimension(cols, rows);
        setSize(dim);
        setPreferredSize(dim);
    }
       
    /** Change the image to the one given by map.
        Precondition: map != null.*/
    public void formImage(ImageMap map) {
        int c= map.getCols();
        int r= map.getRows();
        image= createImage(new MemoryImageSource(c,r,map.getMap(),0,c));
        Dimension dim= new Dimension(c, r);
        setPreferredSize(dim);
        setSize(dim);
    }
    
    /** Paint the image on this JPanel. The system calls
        paint whenever it has to redraw this JPanel */
    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, this);
    }
    
}



