/Users/lyon/j4p/src/j2d/gui/ImagePanel.java

1    // Glenn Josefiak 
2    // Fairfield University 
3    // SW513 
4    // Spring 2003 
5     
6    package j2d.gui; 
7     
8    // Standard libraries 
9     
10   import javax.swing.*; 
11   import java.awt.*; 
12    
13   /** 
14    * This is a panel that displays an image.  It resizes itself to 
15    * accommodate the underlying image. 
16    */ 
17   public class ImagePanel extends JPanel { 
18       Image imgDisplayedImage = null; 
19       int intImageHeight = 0; 
20       int intImageWidth = 0; 
21    
22       /** 
23        * Construct a new image panel (not yet containing an image). 
24        */ 
25       public ImagePanel() { 
26           setPreferredSize(new Dimension(0, 0)); 
27       } 
28    
29       /** 
30        * Override the width reporting so that it's guaranteed to be 
31        * the width of the underlying image. 
32        */ 
33       public int getWidth() { 
34           return intImageWidth; 
35       } 
36    
37       /** 
38        * Override the heigth reporting so that it's guaranteed to be 
39        * the height of the underlying image. 
40        */ 
41       public int getHeight() { 
42           return intImageHeight; 
43       } 
44    
45       /** 
46        * Override the panel's paint method to display the image. 
47        */ 
48       public void paint(Graphics g) { 
49           if (imgDisplayedImage != null) { 
50               g.drawImage(imgDisplayedImage, 0, 0, this); 
51           } 
52       } 
53    
54       /** 
55        * Specify the image to be painted on the panel. 
56        */ 
57       public void setImage(Image img) { 
58           MediaTracker mt = new MediaTracker(this); 
59    
60           imgDisplayedImage = img; 
61           mt.addImage(imgDisplayedImage, 0); 
62    
63           // Load the image completely. 
64    
65           try { 
66               mt.waitForID(0); 
67           } catch (InterruptedException e) { 
68               // do nothing for now if image fails to load. 
69               return; 
70           } 
71    
72           // Get height and width of the new image.  Pass a null 
73           // ImageObserver to the height and width functions since 
74           // we know they will return valid values by virtue of 
75           // using the MediaTracker. 
76    
77           intImageWidth = imgDisplayedImage.getWidth(null); 
78           intImageHeight = imgDisplayedImage.getHeight(null); 
79    
80           setPreferredSize(new Dimension(intImageWidth, intImageHeight)); 
81           repaint(); 
82       } 
83    
84       /** 
85        * Obtain a handle to the image 
86        */ 
87    
88       public Image getImage() { 
89           return imgDisplayedImage; 
90       } 
91   }