19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

27 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />

28 frame.setVisible(true);<br />

29 }<br />

30 }<br />

13.11 Case Study: The ImageViewer Class 507<br />

FIGURE 13.25<br />

Six images are displayed in six ImageViewer <strong>com</strong>ponents.<br />

The ImageViewer class is implemented in Listing 13.13. (Note: You may skip the implementation.)<br />

The accessor and muta<strong>to</strong>r methods for the properties image, stretched,<br />

xCoordinate, and yCoordinate are easy <strong>to</strong> implement. The paintComponent method<br />

(lines 27–36) displays the image on the panel. Line 30 ensures that the image is not null<br />

before displaying it. Line 31 checks whether the image is stretched or not.<br />

LISTING 13.13<br />

ImageViewer.java<br />

1 import java.awt.*;<br />

2 import javax.swing.*;<br />

3<br />

4 public class ImageViewer extends JPanel {<br />

5 /** Hold value of property image */<br />

6 private java.awt.Image image;<br />

7<br />

8 /** Hold value of property stretched */<br />

9 private boolean stretched = true;<br />

10<br />

11 /** Hold value of property xCoordinate */<br />

12 private int xCoordinate;<br />

13<br />

14 /** Hold value of property yCoordinate */<br />

15 private int yCoordinate;<br />

16<br />

17 /** Construct an empty image viewer */<br />

18 public ImageViewer() {<br />

19 }<br />

20<br />

21 /** Construct an image viewer for a specified Image object */<br />

22 public ImageViewer(Image image) {<br />

23 this.image = image;<br />

24 }<br />

25<br />

26 @Override<br />

27 protected void paintComponent(Graphics g) {<br />

28 super.paintComponent(g);<br />

29<br />

30<br />

31<br />

if (image != null)<br />

if ( isStretched() )<br />

32 g.drawImage(image, xCoordinate, yCoordinate,<br />

33 getWidth(), getHeight(), this);<br />

34 else<br />

35 g.drawImage(image, xCoordinate, yCoordinate, this);<br />

36 }<br />

implementation<br />

skip implementation?<br />

properties<br />

construc<strong>to</strong>r<br />

construc<strong>to</strong>r<br />

image null?<br />

stretched<br />

nonstretched

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!