import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/** DemoImage2 - demonstrate putting an image in a painting panel.<p>
*
* This demo is a bit fancier than <code>DemoImage</code>.
* The image is preloaded using
* <code>MediaTracker</code>.  After the image is loaded, we
* determine the size of the image and then make the paint
* panel just size needed to display the image.<p>
*
* Screen snap...<br>
* <center><img src="DemoImage2.gif"></center><p>
*
* @see <a href="DemoImage2.java">source code</a>
* @author Scott MacKenzie, 2002
*/
public class DemoImage2
{
   public static void main(String[] args)
   {
      // use look and feel for my system (Win32)
      try {
         UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
      } catch (Exception e) {}

      DemoImage2Frame frame = new DemoImage2Frame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setTitle("DemoImage2");
      frame.pack();
      frame.show();
   }
}

class DemoImage2Frame extends JFrame
{
   DemoImage2Frame()
   {
      Image image = Toolkit.getDefaultToolkit().getImage("varihall.jpg");

      // get and print the width and height of the image (doesn't work!)

      int w = image.getWidth(this);
      int h = image.getHeight(this);
      System.out.println("width = " + w + ", height = " + h);

      // use a MediaTracker to track the loading of the image

      MediaTracker mt = new MediaTracker(this);

      // beginning loading the image

      mt.addImage(image, 0);

      // wait until the image is loaded

      try
      {
         mt.waitForID(0);
      } catch (InterruptedException e) {}

      // get and print the width and height of the image (Now it works!)

      w = image.getWidth(this);
      h = image.getHeight(this);
      System.out.println("width = " + w + ", height = " + h);

      // create a paint panel containing the image

      PaintPanel pp = new PaintPanel(image);

      // make the panel just the size needed

      pp.setPreferredSize(new Dimension(w, h));

      // make the paint panel this JFrame's content pane

      this.setContentPane(pp);
   }

   class PaintPanel extends JPanel
   {
      Image image;
   
      public PaintPanel(Image imageArg)
      {
         image = imageArg;
      }
   
      public void paintComponent(Graphics g)
      {
         super.paintComponent(g);         //paint background
         g.drawImage(image, 0, 0, this);  // draw the image
      }
   }
}

