Page 217 - Introduction to Programming with Java: A Problem Solving Approach
P. 217
5.9 GUI Track: Drawing Images, Lines, Rectangles, and Ovals in Java Applets (Optional) 183
Before you can use a picture in a program, you need to know how big it is—its width and height in numbers of pixels. Pixels are the tiny dots of color a computer uses to display something on its screen. Fig- ure 5.14 contains a program you can use to determine the pixel width and pixel height of the contents of an image file. The program imports Java’s Scanner class to retrieve a keyboard entry of the filename, and it imports Java’s ImageIcon class to read the image file and determine image properties. After prompting the user for a filename, the program uses that name to create an object we call icon, which manages in- formation transfer from the image file—like our stdIn object manages information transfer from the key- board. The getWidth and getHeight methods return the image’s width and height in pixels. This gives the default size of the area required to display the image on a computer screen.
/*************************************************************
*
ImageInfo.java
Dean & Dean
This supplies width and height of an image.
*************************************************************/
*
*
*
import java.util.Scanner;
import javax.swing.ImageIcon;
public class ImageInfo
{
}
// end ImageInfo
staticAvpoiad gmaoin(SPtrDinFg[]Eanrghs)ancer Scanner stdIn = new Scanner(System.in);
ImageIcon icon;
System.out.print("Enter image filename: ");
icon = new ImageIcon(stdIn.nextLine());
System.out.println("image width = " + icon.getIconWidth());
System.out.println("image height = " + icon.getIconHeight());
public
{
}
Sample session:
Enter image filename: hurricanes.jpg
image width = 640
image height = 427
Figure 5.14 ImageInfo program determines the width and height of an image in an image file Graphics Class Methods
The Java API class called Graphics contains several methods for displaying images and geometric shapes. Figure 5.15 presents API headings and descriptions for some of these methods. Notice that these headings do not have static modifiers. This means that you must use an object of the Graphics class to call all of these methods, just like you must use a String object to call most of the methods of the String class. This Graphics object contains a reference to the window on which things are drawn, and it contains other