Click to See Complete Forum and Search --> : NullPointerException in Panel


staun
May 3rd, 2000, 03:00 PM
Hi there,

How come you cant do this in a class that extends Panel:

Image image = createImage( 20, 30);
Graphics g = image.getGraphics();

The last line throws a NullPointerException at runtime. Do the Panel need to implement something ???

Soren Staun Jorgensen
CADeye

lone_wolf_1985
May 3rd, 2000, 07:35 PM
The most likely reason that your program throws a NullPointerException is because your panel hasn't created its peer yet. To do this, either add the line "addNotify();" before those two lines or wait until the panel is visible, then add those two lines.

Here is the first example:

addNotify();
Image image = createImage(20, 30);
Graphics g = image.getGraphics();




If that didn't work, then you have to make sure that the panel is visible, then you can add those lines.
Here's that example:

setVisible(true);
Image image = createImage(20, 30);
Graphics g = image.getGraphics();




Also, make sure that you add the panel to another container, okay?

kib63613
May 3rd, 2000, 07:38 PM
This might be the case that the native peer of the panel is not created. Hence, the graphics context is
null. The obvious example is that the panel should be shown on the applet, or shown on the frame if
it is the application. If it is shown, the graphics context that you want to get will not be the null. In
this case, you should get the graphics context.
That is the reason why we can createImage and getGraphics in the applet or frame in the application,
but can not do the same thing in the panel directly.
good luck,
Alfred Wu