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);
    }
    
    /** Store this image in file fname in format form */
    public void write(String fname, String form) throws java.io.IOException {
      // Make sure that the image in currentMap is OK.
      //Image image= currentMap.getImage();
       BufferedImage bimage= 
          new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    
      Graphics g= bimage.createGraphics();

      g.drawImage(image, 0, 0, null);
      g.dispose();
      File f= new File(fname);
      if (f.exists()) {
          System.out.println("File " + f.getAbsolutePath() + " exists. It was not overwritten.");
          return;
      }
      ImageIO.write(bimage, form, f);
      System.out.println("Image written to " + f.getAbsolutePath());
    }  
    
}



