Image Buffers...

Im trying to write a component that peoduces a nice graphics effect, and I want it to be compatable with IE 4...

The problem is making a buffered image to use, and getting it's handle.

In Java 2, I have been using:

private BufferedImage buffImage=new BufferedImage(360,370,BufferedImage.TYPE_INT_RGB);

which has been fine, but doesn't work in IE 4, so I can't use it.

So I wrote a small method thusly:

  private void createBufferedImage()
    {
    bufferedImage=createImage(sourceBitmapWidth,sourceBitmapHeight);
    buffer=bufferedImage.getGraphics();
    }

It's great but it stops every single time with a null pointer exception when the JVM gets to the getGraphics() method, DAMN!

I was reading a book, and it said put it in your paint(Graphics g) method, like so:

public void paint(Graphics g)
  {
  if(buffer==null)
    bufferedImage=createImage(sourceBitmapWidth,sourceBitmapHeight);
    buffer=bufferedImage.getGraphics();
    }

   buffer.blah blah blah............  

   g.drawImage(bufferedImage,0,0,this);
  }

This version works! But two things I dont understand...

Why does the very same createImage folowed by getGraphics commands work in the paint method, but not in my createBufferedImage method, which always throws that exception, and why do I have to create my buffer in the paint method, EVERY time checking to see if it's been produced already? I just want to create it, and refere to it FROM paint, not mess around checking if it exists in there!

If you really want, I can supply the full code...
LVL 1
Lab_RatAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
imladrisConnect With a Mentor Commented:
The issue, I believe, is one of timing. The createImage method depends on the Component being drawn on the screen. Since painting is completely asynchronous in Java, and since such createImage calls are frequently made early on, it is likely that the Component is not yet "shown" on the screen, in which case the createImage will fail, and so the getGraphics returns null.

Putting it in the paint method provides a reasonable place to make (a number of) tries at getting it.
0
 
Lab_RatAuthor Commented:
lol!
Thanks for the input imladris! Although you didn't address the optimisation problem of having -mostly- redundant code in the paint method(an 'if' statement that only ever is true once...), you are the only person to comment!

Hence your A, and 100 points...

:o)

Thank you.
0
All Courses

From novice to tech pro — start learning today.