Painting the Image


Now that the user has loaded a new image, you have to make sure that it appears when the window is redrawn. You can do that in the paint method. There's not going to be a lot of fancy animation in this application, so it doesn't use any double buffering. All it does is draw the current image when required in the paint method.

The paint method first makes sure there actually is a BufferedImage object to draw:

 public void paint(Graphics g) {     if(bufferedImage != null){     .     .     .     } } 

If there is an image to draw, you can use the Graphics object passed to the paint method to paint that image, using the Graphics object's drawImage method. Even though that method is usually passed an Image object, you can also pass it a BufferedImage object and it'll be automatically cast to an Image object.

Here's how you can draw the loaded image centered in the window (the last parameter passed to the drawImage method here corresponds to an ImageObserver object if you want to use one to monitor the imagethis application doesn't use an ImageObserver object, so it simply passes a pointer to the current object for this parameter):

 public void paint(Graphics g) {     if(bufferedImage != null){         g.drawImage(bufferedImage, getSize().width / 2             - bufferedImage.getWidth() / 2,             getInsets().top + 20, this);     } } 

This draws the newly loaded image, and the results appear in Figure 3.1, where, as you can see, the figure is centered in the client area and above the buttons.

Not bad.

So what about saving images?



    Java After Hours(c) 10 Projects You'll Never Do at Work
    Java After Hours: 10 Projects Youll Never Do at Work
    ISBN: 0672327473
    EAN: 2147483647
    Year: 2006
    Pages: 128

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net