0

I am new to java graphics, and am confused as to why my setSolor throws a nullpointer. Trying to do something simple like this:

public void drawEllipse(int x, int y, Color color){
    Graphics g = null;
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(color);
    Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y,1,1);
    g2.draw(ellipse);
}
1
  • Okay, this one kinda leaps off the page as soon as you focus on the code. You've got g.equals(g2)==true. I'm saying thats a valid statement. Take out what's there and do it like the book tells you. Commented Oct 11, 2015 at 19:12

1 Answer 1

2

Well the problem is that you init g with null and therefore g2 is also null which causes the Exception

Edit:

If you want paint something with AWT you should overwrite the paint method. There you will get an Graphics Object. Or you call getGraphics on the container which will also gives you an Graphics Object.

But i think the first variant is the one to use in general

Sign up to request clarification or add additional context in comments.

3 Comments

how do I create a new graphics object/what is the proper form? the compiler doesn't let me do Graphics g = new Graphics()
thanks for being polite, total brain fart on my part. sometimes you write something to make the compiler happy and forget why!
Don't, ever, use getGraphics, it's not how painting works in Swing, apart from been able to return null, it represents nothing more then a snapshot of what was painted on the last paint cycle, meaning that at any point in the future it could be replaced. Better to use paintComponent of the Swing component,t this way you know when you need to update the graphics

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.