13.13. (Optional) Displaying Images |
You learned how to create image icons and display them in labels and buttons in §12.10, "Image Icons." For example, the following statements create an image icon and display it in a label:
ImageIcon icon = new ImageIcon( "image/us.gif" ); JLabel jlblImage = new JLabel(imageIcon);
An image icon displays a fixed- size image. To display an image in a flexible size, you need to use the java.awt.Image class. An image can be created from an image icon using the getImage() method as follows :
Image image = imageIcon.getImage();
Using a label as an area for displaying images is simple and convenient , but you don't have much control over how the image is displayed. A more flexible way to display images is to use the drawImage method of the Graphics class on a panel. Four versions of the drawImage method are shown in Figure 13.22.
ImageObserver is an asynchronous update interface that receives notifications of image information as the image is constructed . The Component class implements ImageObserver . Therefore, every GUI component is an instance of ImageObserver . To draw images using the drawImage method in a Swing component, such as JPanel , override the paintComponent method to tell the component how to display the image in the panel.
Note
You can also create an ImageIcon from an Image object using new ImageIcon(image) . |
Listing 13.13 gives the code that displays an image from image/us.gif . The file image/us.gif (line 12) is under the class directory. The Image from the file is created in lines 11 “14. The drawImage method displays the image to fill in the whole panel, as shown in Figure 13.23.
1 import java.awt.*; 2 import javax.swing.*; 3 4 public class DisplayImage extends JFrame { 5 public DisplayImage() { 6 add( new ImageCanvas()); 7 } 8 9 public static void main(String[] args) { 10 JFrame frame = new DisplayImage(); 11 frame.setTitle( "DisplayImage" ); 12 frame.setSize( 300 , 300 ); 13 frame.setLocationRelativeTo( null ); // Center the frame 14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15 frame.setVisible( true ); 16 } 17 } 18 19 class ImageCanvas extends JPanel { 20 ImageIcon imageIcon = new ImageIcon( "image/us.gif" ); 21 Image image = imageIcon.getImage(); 22 23 /** Draw image on the panel */ 24 public void paintComponent(Graphics g) { 25 super .paintComponent(g); 26 27 if (image != null ) 28 g.drawImage(image, , , getWidth(), getHeight(), this ); 29 } 30 } |