Trying to draw a 2D shape, but Graphics2D is null, what am I doing wrong?

At this point, I just want a shape to appear. But when I call draw(...), I get a NullPointer. Turns out when I call getGraphics() on the input JFrame (which does show up properly when the rest is commented out), I get nothing. Maybe it's the casting, I don't know enough about this issue to really say. If anyone out there has worked with 2D primitives and can shed some light on the problem, I would appreciate it.
Thanks for any help.
public class BatteryDisplay extends JPanel {
     Graphics2D g2d;
     Rectangle2D.Double rect1;
     JFrame jf;
     public BatteryDisplay(JFrame jf)
          this.jf = jf;
                // Is there another way to get the graphics object?
          g2d = (Graphics2D) jf.getGraphics();
          createRectangle();
          drawRectangle();
     public void createRectangle()
          rect1 = new Rectangle2D.Double(100,100,200,50);
          System.out.println(rect1.height);
                // The next line returns the NullPointer, so g2d is NOT initalized
          System.out.println(g2d);
     public void drawRectangle()
          this.g2d.draw(rect1);
}

Your painting functions should be initiated from an overridden paintComponent, not from the constructor. A graphics object will be provided to you there.
[http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html]

Similar Messages

Maybe you are looking for

  • Unable to get checkbox working in Apex 3.2.1.00.10

    We recently upgraded our production application running on apex to Apex 3.2.1.00.10. Everything works, except for the query that generates the check-box. This used to do so in the previous version 3, but does not work anymore, the code is the same...

  • ISight image is too dark

    I bought this iSight used from a friend and the image is too dark. My friend never used it so, he doesn't know anything. When I use iChat, Skype or Photobooth, the image is just too dark. I have looked endelessly for a solution and can't seem to find

  • [SOLVED] USB storage devices do not appear as /dev/ block devices

    Hello. I'm experiencing the exact same problem described in this thread and this thread I'm running linux-ck-ivybridge. Both of these threads are marked solved but I don't get their solutions. Could someone help me understand what all this means? I t

  • Cant find update Finalcut X

    Why my Mac cant find the update of final cut X ?? I click on the software update but there are no updates Is it cos I have Final cut Pro 7  and the finalcut X is in an other folder ?

  • Verdana Font not printing properly using Vista and Acrobat Pro v8

    Has anyone got any ideas as to how I can fix this problem.  When I send a word doc to the pdf printer that is all in verdana font it prints out gibberish, however, if in aerial or times new roman thats fine.  I'm using Vista and printing via a termin