Hi!
I was wondering if someone's already checked this statement that says : Innefficiency of MediaTracker w/o ImageObserver and vice-versa.
Because of some reasons, some web articles (
http://www.sdv.fr/pages/casa/html/java-image.html and other posts in various forums) discussed this topic and but miss-spelled the relationship between these 2 Java Classes, as the MediaTracker's would be used in place of ImageObserver's.
I'd rather state that
nor the MT nor the IObs can be used standing alone. They are related ! As someone says, they're cousins and they can't live one w/o each other.
Do you agree ?
Hence, buffered painting becomes easier only if BOTH of these classes are linked together with the SAME component. Let's have a unit test :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import java.awt.*; import java.awt.image.*; import java.awt.event.*; import javax.swing.*; class MainBufferedPainting { class ImageComponent extends JComponent { public Component obs; public MediaTracker mt; public Image[] img; public void paint(Graphics g) { try { int rowIndex = 0; for(int index = 0; index < img.length; index++) { mt.waitForID(index); Point pos = new Point( (int)((double)getWidth() - (double)img[index].getWidth(obs) / 2.0), rowIndex ); g.drawImage(img[index], pos.x, pos.y, obs); rowIndex += img[index].getHeight(obs); } } catch(InterruptedException e) { e.printStackTrace();} } } public ImageComponent getComponent() { return new ImageComponent(); } public static void main(String[] args) { JFrame f = new JFrame("Buffered Painting"); MainBufferedPainting.ImageComponent comp = new MainBufferedPainting().getComponent(); comp.img = new Image[]{ new BufferedImage(50,50, BufferedImage.TYPE_INT_ARGB), Toolkit.getDefaultToolkit().getImage("myImage.jpg"), GraphicsEnvironment. getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().createCompatibleVolatileImage(50, 50) }; MediaTracker mt = new MediaTracker(f); for(int i = 0; i < comp.img.length; i++) mt.addImage(comp.img[i], i); ImageObserver obs = (ImageObserver)f; comp.obs = f; comp.mt = mt; comp.setPreferredSize(new Dimension(500,500)); f.getContentPane().add(comp); f.pack(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }}); f.setLocationRelativeTo(null); f.setVisible(true); try { while(true) { Thread.sleep(100); f.repaint(); } } catch(InterruptedException e) { e.printStackTrace(); System.exit(0); } } } |
hence this be an assertion rule :
the MediaTracker target (ImageObserver) must be equal to the Graphics ImageObserver otherwise painting will fail with no picture rendered. Can someone get this validated, too ?