Game-of-Life-WSU-CEG4180  v0.1
RefactoringtheGameofLife
ImageComponent.java
Go to the documentation of this file.
1 /* This page is part of the Game of Life source code */
2 
3 /*
4  * Easily add images to your UI
5  * Copyright 2003 Edwin Martin <edwin@bitstorm.org>
6  *
7  */
8 package org.bitstorm.util;
9 
10 import java.awt.Canvas;
11 import java.awt.Dimension;
12 import java.awt.Graphics;
13 import java.awt.Image;
14 import java.awt.MediaTracker;
15 import java.awt.image.ImageObserver;
16 
17 
18 /**
19  * A component to add a image to (e.g.) a panel.
20  *
21  * Supports animated GIF's.
22  *
23  * @author Edwin Martin
24  */
25 public class ImageComponent extends Canvas implements ImageObserver {
26  private Image image;
27 
28  /**
29  * Constucts a ImageComponent.
30  *
31  * This constructor uses the MediaTracker to get the width and height of the image,
32  * so the constructor has to wait for the image to load. This is not a good idea when
33  * getting images over a slow network. There is a timeout of 3 sec.
34  *
35  * Maybe one time the MediaTracker can be replaced, so it returns when the width and height
36  * are known, not when the whole image is loaded. Then the constructor will be much faster and
37  * better suited for loading images over a slow connection.
38  *
39  * @param image the image to show
40  */
41  public ImageComponent( Image image ) {
42  this.image = image;
43  MediaTracker tracker = new MediaTracker( this );
44  tracker.addImage( image, 0 );
45  try {
46  // Wait max 3 sec
47  tracker.waitForID(0, 3000);
48  } catch (InterruptedException e) {
49  // oops. no image.
50  }
51  }
52 
53  /**
54  * Draw the image.
55  *
56  * @see java.awt.Component#paint(java.awt.Graphics)
57  */
58  public void paint(Graphics g) {
59  g.drawImage( image, 0, 0, this );
60  }
61 
62  /**
63  * Returns preferred size. At the first pack()ing of the Window, the image might nog be completely
64  * read and getPreferredSize() might return the wrong size. imageUpdate() corrects this.
65  * @see java.awt.Component#getPreferredSize()
66  */
67  public Dimension getPreferredSize() {
68  return new Dimension( image.getWidth( this ), image.getHeight( this ) );
69  }
70 
71  /**
72  * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
73  */
74 
75  public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
76  boolean isImageRead = ( infoflags & ImageObserver.ALLBITS ) != 0;
77  repaint();
78  return ! isImageRead; // return true while image not completely read
79  }
80 
81 }
boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)