Skip to main content
gamedev.net
🔒 Locked

[java] Null Pointer Exception in Graphics Class...

Started by VoytekG 1 reply 500+ views
Original Post
VoytekG
VoytekG
Hey! I am currently making a small program in Java that runs in a console window. The program has to create an image and save it to a file. I have the file saving code, and I can create the image. The code I am using to create the image is below:
// Create the image.
Applet testMe = new Applet();
		
Image myBuffer = testMe.createImage(201,201);
		
Graphics bufferG = myBuffer.getGraphics();
		
bufferG.setColor(Color.black); // ERROR
bufferG.fillRect(0,0,201,201); // ERROR
 
However, when I run the code, I get a Null Pointer Exception error at the two lines that say there is an error. Can anyone tell me what I am doing wrong? By the way, the whole thing is in a public static void main (String [] args) method. Thanks, Voytek http://www.liquidsoftware.cjb.net Games, apps, and more!
http://www.liquidsoftware.cjb.netGames, apps, and more!
cwraith
cwraith
The problem with that approach is that a graphics object returned by a container''s getGraphics() method is null until the container has been realized, which is the process that creates its native peer.

A much better approach is to just create a BufferedImage, and use it. That way you''ll avoid dealing with native peers entirely. Here''s a block of code taken from a simple servlet I wrote which dynamically generates jpgs. (w, h, and c are defined earlier in the method, and aren''t really important for this demo.)


  

BufferedImage bi =
new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();

g.setColor(new Color(c));
g.fillRect(0, 0, w, h);

g.dispose();

resp.setHeader("content-type", "image/jpeg");

OutputStream os = resp.getOutputStream();
ImageIO.write(bi, "jpg", os);
os.close();

VoytekG
VoytekG
Hey!

Thank you for your help! The BufferedImage works great!

-Voytek

http://www.liquidsoftware.cjb.net
Games, apps, and more!
http://www.liquidsoftware.cjb.netGames, apps, and more!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.