
// ImagePanel.java
// Michael Kolling and David J Barnes 
// Modified by Andrew Davison, Jan 2018, ad@fivedots.coe.psu.ac.th

/* ImagePanel is a JPanel that can load and display a BufferedImage
   by drawing the image onto itself.
*/

import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;


public class ImagePanel extends JPanel
{
  private int width, height; // of this panel
  private BufferedImage panelImage; // for holding the image


  public ImagePanel()
  {
    width = 360; // arbitrary size for empty panel
    height = 240;
    panelImage = null;

    setBackground(Color.WHITE);
  }  // end of ImagePanel()


  public void displayImage(File f)
  // load and set the image for this panel
  {
    BufferedImage image = loadImage(f);
    if (image != null) {
      width = image.getWidth();
      height = image.getHeight();
      panelImage = image;

      invalidate();
      repaint();   // triggers a panel redrawing with the new image
    }
  }  // end of displayImage()
    


  private BufferedImage loadImage(File imageFile)
  // load an image file and return it as a BufferedImage.
  {
    try {
      BufferedImage image = ImageIO.read(imageFile);
      if (image == null || (image.getWidth(null) < 0))
        // we could not load the image - probably invalid file format
        return null;
      return image;
    }
    catch (IOException e) 
    {  return null; }
  }  // end of loadImage()



  // ----- redefined methods inherited from JPanel ---------------
   
  public Dimension getPreferredSize()
  /* Say how big we would like this panel to be.
     This method gets called by layout managers when placing,
     and sizing this panel in the JFrame. */
  {   return new Dimension(width, height); }
    

  public void paintComponent(Graphics g)
  /* Draw the image onto the panel.
     This method gets called by the JVM every time it want to 
     display (or redisplay) this panel. */
  {
    super.paintComponent(g);  // repaint standard stuff first

    Dimension size = getSize();
    g.clearRect(0, 0, size.width, size.height);
    if (panelImage != null)
      g.drawImage(panelImage, 0, 0, null);
  }  // end of paintComponent()


}  // end of ImagePanel class
