• Advertisement
Sign in to follow this  

[java] java.awt.Graphics.setColor throwing NullPointerException

This topic is 2772 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a Graphics object which I'm using as a context to a backbuffer. My Window class inherits from a JFrame and holds a private Graphics called m_bufferGraphics which is initialised by calling getGraphics on the Image used as the actual drawing surface of the buffer.

Here is my class declaration and constructor, I've left a few irrelevant parts out for brevity:

public class GameWindow extends JFrame

private Graphics m_bufferGraphics; // context to the backbuffer for draw methods
private Image m_backBuffer; // the backbuffer image where the display will be built before the image is drawn to the window

static final int WINDOW_WIDTH = 1680;
static final int WINDOW_HEIGHT = 1050;

public GameWindow(EntityManager entityManager)

this.setVisible(true); // need to set the window as visible here or the backbuffer won't be created

setLayout(new BorderLayout());

m_backBuffer = createImage(WINDOW_WIDTH, WINDOW_HEIGHT);
m_bufferGraphics = m_backBuffer.getGraphics(); // a graphics context for the backbuffer so we can draw to it


The issue occurs where I try to set the colour that m_bufferGraphics is using, with just
Despite the documentation saying getColor doesn't throw, it's throwing NullPointerException. In the following fragment from my 'void paint(Graphics g)' method...

catch (NullPointerException e)
int debug = 0;

...I have a breakpoint on the 'int debug = 0' line which triggers just once - on subsequent calls to paint() it doesn't throw the exception. Indeed, a few lines past this I change the colour again and that line doesn't throw.

I can catch the exception and just not bother handling it (which seems to have no effect on the game) so it's not a *massive* problem, but it would be nice to know what's causing it.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement