CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2000
    Location
    Denmark
    Posts
    17

    NullPointerException in Panel

    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

  2. #2
    Join Date
    Apr 2000
    Location
    Canada
    Posts
    27

    Re: NullPointerException in Panel

    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?


  3. #3
    Join Date
    Dec 1999
    Location
    Chonghe, Taipei County, Taiwan, R.O.C.
    Posts
    231

    Re: NullPointerException in Panel

    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


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured