Java Reference
In-Depth Information
13.11 Case Study: The ImageViewer Class
This case study develops the ImageViewer class for displaying an image in a panel.
Key
Point
Displaying an image is a common task in Java programming. This case study develops a
reusable component named ImageViewer that displays an image on a panel. The class con-
tains the properties image , stretched , xCoordinate , and yCoordinate , with associated
accessor and mutator methods, as shown in Figure 13.24.
javax.swing.JPanel
The get and set methods for these
data fields are provided in the class, but
omitted in the UML diagram for brevity.
ImageViewer
-image: Image
-stretched: boolean
-xCoordinate: int
-yCoordinate: int
Image in the image viewer.
True if the image is stretched in the viewer.
x -coordinate of the upper-left corner of the image in the viewer.
y -coordinate of the upper-left corner of the image in the viewer.
+ImageViewer()
+ImageViewer(image: Image)
Constructs an image viewer with no image.
Constructs an image viewer with the specified image.
F IGURE 13.24
The ImageViewer class displays an image on a panel.
You can use images in Swing components such as JLabel and JButton , but these images
are not stretchable. The image in an ImageViewer can be stretched.
Let us write a test program in Listing 13.12 that displays six images using the
ImageViewer class. Figure 13.25 shows a sample run of the program.
stretchable image
L ISTING 13.12 SixFlags.java
1 import javax.swing.*;
2 import java.awt.*;
3
4 public class SixFlags extends JFrame {
5 public SixFlags() {
6 Image image1 = new ImageIcon( "image/us.gif" ).getImage();
7 Image image2 = new ImageIcon( "image/ca.gif" ).getImage();
8 Image image3 = new ImageIcon( "image/india.gif" ).getImage();
9 Image image4 = new ImageIcon( "image/uk.gif" ).getImage();
10 Image image5 = new ImageIcon( "image/china.gif" ).getImage();
11 Image image6 = new ImageIcon( "image/norway.gif" ).getImage();
12
13 setLayout( new GridLayout( 2 , 0 , 5 , 5 ));
14 add( new ImageViewer(image1));
15 add( new ImageViewer(image2));
16 add( new ImageViewer(image3));
17 add( new ImageViewer(image4));
18 add( new ImageViewer(image5));
19 add( new ImageViewer(image6));
20 }
21
22 public static void main(String[] args) {
23 SixFlags frame = new SixFlags();
24 frame.setTitle( "SixFlags" );
25 frame.setSize( 400 , 320 );
26 frame.setLocationRelativeTo( null ); // Center the frame
create image
create image viewer
 
 
Search WWH ::




Custom Search