.getGraphics in custom rendering method returns null... anyone know why?

Hello,
The problem is pretty much exactly as specified.
Take this class for example:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package vicsanimation;
* @author
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
public class VButton extends JLabel {
    BufferedImage activeImage;
    BufferedImage pressedImage;
    BufferedImage deactiveImage;
    BufferedImage highlightedImage;
    ImageIcon currentImage;
    public VButton (String b1, String b2, String b3, String b4, int x, int y){
        activeImage = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
        try { 
            activeImage = ImageIO.read(new File(b1));
            pressedImage = ImageIO.read(new File(b2));
            deactiveImage = ImageIO.read(new File(b3));
            highlightedImage = ImageIO.read(new File(b4));
        catch (IOException e) {
            System.out.println(e.getMessage());
        this.setSize(activeImage.getWidth(), activeImage.getHeight());
        this.setLocation(x,y);
        this.setVisible(true);
        this.render();      // <----------------- ERROR FROM HERE!!!
    // This is the method used to render the button. It does not use the paint method
    // because the application can use FullScreen mode.
    public void render(){
        Graphics2D buttonGraphics = (Graphics2D)this.getGraphics();
            buttonGraphics.drawImage(activeImage, null, 0, 0);
            System.out.println("Image drawn successfully");
}If I run this code, I get a Null-Pointer exception thrown from the last method. This is because the "buttonGraphics" object is null.
I do know a work-around, although I'd really like to know exactly why this is happening.
The work-around is simply to remove the this.render() call at the end of the constructor, create the button in an outside container object, and then call the render() method from the object that contains the button. For example:
    private void initScreen(){
        ..... snip ....
        VButton closeButton = getCloseButton();
        this.add(closeButton);
        closeButton.render();
        ..... snip .....
    }If anyone could explain to me why this happens (in non-Java expert language) I'd be very thankful.

Thanks again for your help.
I'm sure the solution to every problem is in the API if one were to look hard enough!
But obviously the API is massive and I suppose you learn these things from experience more than committing that kind of stuff to memory. If I were to scour the API looking for solutions to things which I only barely understand to start with I'd go mad. Let alone be there for several days.
So thanks for helping out, I really appreciate it!
Edited by: wombatvvv on Jul 23, 2008 3:23 PM

Similar Messages

  • Looks like some Exceptions' getMessage() methods return null

    Looks like some Exceptions' getMessage() methods return null instead of the message.
    -Andrew

    snidely_whiplash wrote:
    Looks like some Exceptions' getMessage() methods return null instead of the message.
    -AndrewDoes it return a null object, or does it return "null" as a String? The latter may be a case of using the message from a wrapped exception, which in case of a NullPointerException is frequently null (if the NPE was not constructed intentionally with a message).
    BR,
    Robert

  • TS1967 i have a problem when i try to update or install apps in my ipad, and a message come up says "can not connect to Itunes Store", anyone know why? please advise. however i had update all my detail of payment method.

    i have a problem when i try to update or install apps in my ipad, and a message come up says "can not connect to Itunes Store", anyone know why? please advise. however i had update all my detail of payment method.

    Settings > General > Reset > Reset Network Settings.
    Power cycle the router.
    Basic troubleshooting from the User's Guide is reset, restart, restore (first from backup then as new).  Try each of these in order until the issue is resolved.

  • Code not working, anyone know why?

    I'm making a simple pong game, and it's important to me that I use JAVA as efficient as possible (that is, use object orientated stuff, mostly). So, for drawing the ball and the players, I had thought up the following steps:
    - the applet has an array list that contains drawables*
    - if the ball and players need to be drawn, the applet uses a for-each loop, wich will call the draw(Graphics g) of all the drawables in the array list.
    * interface, guarantees that the method public void draw(Graphics g) is pressent.
    This is how I programmed it:
    http://willhostforfood.com/access.php?fileid=32821
    Only problem is, it doesn't work. The method paint() of the applet should result in "Hello World" being drawn on the screen (I know this seems like an eleborate method, but using seperate objects will help organise things once I have like, 20 - 30 balls on screen), but it doesn't.
    Does anyone know why it is not working?

    Here ya go, this is something I did quite a while ago, knock yourself out:
    package RandomColor;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.awt.Image;
    import java.awt.image.MemoryImageSource;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import java.awt.Point;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.util.Random;
    public class RandomColor extends JFrame implements MouseListener, MouseMotionListener, MouseWheelListener{
      private BufferedImage myImage = null;
      private Canvas myCanvas = null;
      private Color bgColor = Color.BLACK;
      public RandomColor() throws java.lang.Exception {
        super();
        setUndecorated(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBackground(bgColor);
        Dimension myDimension = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(myDimension);
        setMinimumSize(myDimension);
        JPanel myJP = new JPanel();
        myJP.setBackground(bgColor);
        Dimension dImage = new Dimension(this.getAccessibleContext().getAccessibleComponent().getSize());
        myCanvas = new Canvas();
        myCanvas.addMouseListener(this);
        myCanvas.addMouseMotionListener(this);
        myCanvas.addMouseWheelListener(this);
        myCanvas.setSize(dImage.width, dImage.height);
        myJP.add(myCanvas);
        add(myJP);
    // start of code to hide the cursor   
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor");
        getContentPane().setCursor(transparentCursor);
    // end of code to hide cursor   
        pack();
        setVisible(true);
        Random myR = new Random();
        myImage = new BufferedImage((int) (dImage.getWidth()+0.99), (int) (dImage.getHeight()+0.99), BufferedImage.TYPE_INT_RGB);
        int i = myImage.getWidth();
        int j = myImage.getHeight();
        Ball[] myBall = {new Ball(), new Ball(), new Ball()};
        for (int k=0; k<myBall.length; k++){
          myBall[k].setBackGroundColor(Color.BLACK);
          myBall[k].setBounds(0, i, 0, j);
          myBall[k].setRandomColor(true);
          myBall[k].setLocation(myR.nextInt(i), myR.nextInt(j));
          myBall[k].setMoveRate(32, 32, 1, 1, true);
          myBall[k].setSize( 289, 167);
        Graphics g = myImage.getGraphics();
        while(true) {
          for (int k=0; k<myBall.length; k++){
            g.setColor(myBall[k].fgColor);
            g.fillOval(myBall[k].x, myBall[k].y, myBall[k].width, myBall[k].height);
          invalidate();
          paint(getGraphics());
          for (int k=0; k<myBall.length; k++){
            g.setColor(myBall[k].bgColor);
            g.fillOval(myBall[k].x, myBall[k].y, myBall[k].width, myBall[k].height);
            myBall[k].move();
      public void mouseClicked(MouseEvent e){
        exit();
      public void mouseDragged(MouseEvent e){
    //    exit();
      public void mouseEntered(MouseEvent e){
    //    exit();
      public void mouseExited(MouseEvent e){
    //    exit();
      public void mouseMoved(MouseEvent e){
    //    exit();
      public void mousePressed(MouseEvent e){
        exit();
      public void mouseReleased(MouseEvent e){
        exit();
      public void mouseWheelMoved(MouseWheelEvent e){
        exit();
      private void exit(){
        System.exit(0);
      public void paint(Graphics g){
        super.paint(g);
        myCanvas.getGraphics().drawImage(myImage, 0, 0, null);
      public static void main(String[] args) throws java.lang.Exception {
        new RandomColor();
        System.out.println("Done -- RandomColor");
    }Ball Class:
    package RandomColor;
    import java.awt.Color;
    import java.util.Random;
    public class Ball {
      private int iLeft      = 0;
      private int iRight     = 0;
      private int iTop       = 0;
      private int iBottom    = 0;
      private int moveX      = 1;
      private int moveY      = 1;
      private int xScale     = moveX;
      private int yScale     = moveY;
      private int xDirection = 1;
      private int yDirection = 1;
      private boolean moveRandom = false;
      private boolean colorRandom = false;
      private Random myRand = null;
      public Color fgColor = Color.BLACK;
      public Color bgColor = Color.BLACK;
      public int x = 0;
      public int y = 0; 
      public int width  = 1;
      public int height = 1;
      public Ball(){
        myRand = new Random();
        setRandomColor(colorRandom);
      public void move(){
        x = 5 + x + (xScale*xDirection);
        y = 5 + y + (yScale*yDirection);
        if(x<=iLeft){
          x = 0;
          if(moveRandom) xScale = myRand.nextInt(moveX);else xScale = moveX;
          xDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
        if(x>=iRight-width){
          x = iRight-width;
          if(moveRandom) xScale = myRand.nextInt(moveX);else xScale = moveX;
          xDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
        if(y<=iTop){
          y = 0;
          if(moveRandom) yScale = myRand.nextInt(moveY);else xScale = moveY;
          yDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
        if(y>=iBottom-height){
          y = iBottom-height;
          if(moveRandom) yScale = myRand.nextInt(moveY);else xScale = moveY;
          yDirection *= (-1);
          if(colorRandom) setRandomColor(colorRandom);
      public void setColor(Color c){
        fgColor = c;
      public void setBackGroundColor(Color c){
        bgColor = c;
      public void setBounds(int Left, int Right, int Top, int Bottom){
        iLeft   = Left;
        iRight  = Right;
        iTop    = Top;
        iBottom = Bottom;
      public void setLocation(int x, int y){
        this.x = x;
        this.y = y;
      public void setMoveRate(int xMove, int yMove, int xDir, int yDir, boolean randMove){
        moveX       = xMove;
        moveY       = yMove;
        moveRandom  = randMove;
        xDirection  = xDir;
        yDirection  = yDir;
      public void setRandomColor(boolean random){
        colorRandom = random;
        switch (myRand.nextInt(3)+1){
          case 1:  fgColor = Color.BLUE;
                   break;
          case 2:  fgColor = Color.GREEN;
                   break;
          case 3:  fgColor = Color.RED;
                   break;
          default: fgColor = Color.BLACK;
                   break;
      public void setSize(int width, int height){
        this.width  = width;
        this.height = height;
    }

  • Does anyone know why some Apps won't load unless I buy a new App?

    I've been following a couple of threads. It seems some users, myself included, have a problem where certain Apps will not load. They simply start to open and then return back to the Home screen immediately. When it happens to me (maybe once per week) it's always the same Apps which refuse to load, and they ALL do it - Pages, Keynote, Numbers, Garageband, iMovie, Shareplus all stop working. The reported fix from all users is to go to the AppStore and either update, or buy another App - even a free one. Then all Apps work again properly. It started happening for me after upgrading to iOS 5 but many users had the same issue prior to iOS 5.
    So my question is, does anyone know why this is happening? I don't want to find myself out of 3G signal, or abroad when I've turned Data off, and unable to use my Apps. The fix is useful, but I can't understand why we even need a fix. Suggestions?

    Have you tried a full reset when this happens?  This happens to me on rare occasion and a reset fixes things.

  • HT4199 Every time I introduce the WPA2 passwords I can´t connect. I can only connect to open wi fi networks? Does anyone know why? Thanks

    Every time I introduce the WPA2 passwords I can´t connect. I can only connect to open wi fi networks? Does anyone know why? Thanks

    Some users with various Wi-Fi connection problems have reported that they were given the following instructions by Apple Support, sometimes with success. I can't vouch for this procedure myself. After completing the procedure, you'll have to recreate all your settings in the Network preference pane. Make sure you know how to do that before you begin. Taking screenshots of the preference pane may be helpful.
    Step 1
    Back up all data.
    Triple-click the line below on this page to select it:
    /Library/Preferences/SystemConfiguration
    Right-click or control-click the highlighted line and select
    Services ▹ Reveal
    from the contextual menu.* A folder should open with an item named "SystemConfiguration" selected. Move the selected item to the Trash. You may be prompted for your administrator password.
    *If you don't see the contextual menu item, copy the selected text to the Clipboard (command-C). In the Finder, select
    Go ▹ Go to Folder...
    from the menu bar, paste into the box that opens (command-V). You won't see what you pasted because a line break is included. Press return.
    Step 2
    Reset the System Management Controller

  • When receiving an call waiting can't push the hold and answer button.Because: it will put on hold the first caller, answer to the second, but you can't hear the second until you end the first call !!! Anyone has the same problem ? Did anyone know why ?

    When receiving an call waiting can't push the hold and answer button.Because: it will put on hold the first caller, answer to the second, but you can't hear the second until you end the first call !!! Anyone has the same problem ? Did anyone know why ?

    Contact iTunes Customer Service and request assistance
    Use this Link  >  Apple  Support  iTunes Store  Contact

  • I use Keynote on iPad2. Video out via composite AV cable, audio out through earphone socket. If I plug into the earphone socket first, then the AV cable - no sound. AV first, then earphone - sound. Anyone know why?

    I use Keynote on iPad2. Video out via composite AV cable, audio out through earphone socket. If I plug into the earphone socket first, then plug in the AV cable - no sound. AV first, then earphone - sound. Anyone know why?

    My daughter has had her Razr for about 9 months now.  About two weeks ago she picked up her phone in the morning on her way to school when she noticed two cracks, both starting at the camera lens. One goes completely to the bottom and the other goes sharply to the side. She has never dropped it and me and my husband went over it with a fine tooth comb. We looked under a magnifying glass and could no find any reason for the glass to crack. Not one ding, scratch or bang. Our daughter really takes good care of her stuff, but we still wanted to make sure before we sent it in for repairs. Well we did and we got a reply from Motorola with a picture of the cracks saying this was customer abuse and that it is not covered under warranty. Even though they did not find any physical damage to back it up. Well I e-mailed them back and told them I did a little research and found pages of people having the same problems. Well I did not hear from them until I received a notice from Fed Ex that they were sending the phone back. NOT FIXED!!! I went to look up why and guess what there is no case open any more for the phone. It has been wiped clean. I put in the RMA # it comes back not found, I put in the ID #, the SN# and all comes back not found. Yet a day earlier all the info was there. I know there is a lot more people like me and all of you, but they just don't want to be bothered so they pay to have it fix, just to have it do it again. Unless they have found the problem and only fixing it on a customer pay only set up. I am furious and will not be recommending this phone to anyone. And to think I was considering this phone for my next up grade! NOT!!!!

  • Hi does anyone know why when on certain webpages does my ipad decide to chuck me onto the app screen.

    Hi does anyone know why when on certain webpages does my ipad chuck my to the app screen and if so how do I recitify this.  Thankyou Raylea

    taimsesasta, Not positive, but I was using a picture that had orange in it as my login icon, and when I changed it to a pic that was basically gray, the Apple logo no longer flashed orange. Somehow, it seems, that the Apple logo was momentarily picking up the orange color from my login art and then returning to its normal gray. That's all I know at this point.

  • When I publish a SWF/HTML5 module with Captivate 8 and try to run it using IE9 - I get the following error "The content you are viewing is not supported in the current Document Mode" - anyone know why?

    When I publish a SWF/HTML5 module with Captivate 8 and try to run it using IE9 - I get the following error "The content you are viewing is not supported in the current Document Mode" - anyone know why?

    TLCMediaDesign wrote:
    I've seen a lot of threads about getting rid of these kind of messages. Those messages are there for a reason most of the time. If you have CSS animations or other HTML5 standards that cannot be rendered in IE9 they won't magically start working becuse you got rid of a message. I use IE9 since that is the minimum standard for the client. I have never seen that message publishing to HTML5 content.
    IMO, if your client has IE9 I think that you should develop with IE9 in mind not IE11.
    When you say "develop with IE9 in mind not IE11" do you mean use SWF instead of HTML5? I used the standard question types, and a converted PowerPoint presentation. I didn't add anything out of the ordinary.

  • I cannot make buy anything with my debit card after changing card info.does anyone know why?

    I recently had to get new debit card after losing the other. Does anyone know why?

    Accepted forms of payment  >  http://support.apple.com/kb/HT5552
    Changing Account Information  >  http://support.apple.com/kb/HT1918
    If necessary... Contact iTunes Customer Service and request assistance
    Use this Link  >  Apple  Support  iTunes Store  Contact

  • Email attachments: whenever someone sends me a file the Ipad labels it winmail.dat and wont allow me to open it...these are Word, Exce or jpgs.  Does anyone know why this is and how to fix it?  Also, how can you save attachments to a file on the IPad2

    whenever someone sends me a file the Ipad labels it winmail.dat and wont allow me to open it...these are Word, Exce or jpgs.  Does anyone know why this is and how to fix it?  Also, how can you save attachments to a file on the IPad2

    Is this a particular sender, or all of your attchments?  Google winmail.dat and you will see a number of returns that can explain this, but in short, this is the way some e mail providers deal with attachments.  If all of your e mail is coming that way, you need to change a setting on your isp set up.  Perhaps stary here...
    http://www.nytimes.com/2010/11/25/technology/personaltech/25askk.html

  • Does anyone know why I cant Activate my Iphone 3gs?

    Dpes anyone know why I cant activate my iphone 3gs,it says it cant be activated because the activation server is unavaliable

    If the phone was previously unlocked by an unauthorized method, it was re-locked to its original carrier when you updated.  It will now acivate and operate only with that carrier, using their SIM card.

  • Does anyone know why these particular files would load incorrectly through iphone mail?

    I have been having trouble with some images being sent out correctly to my sales people/customers. There are no problems EXCEPT when the files pass through an iphones mail. Sent or recieved the files get small file corruptions or something that results in an image distortion. I send tons of other images that have had no issue. Does anyone know why these particular ones are different? I'm worried I might be using the wrong settings in my save for web to get everything to be read by others accurately.
    This problem doesn't seem to be limited by just the one email either. Every time we email these images through iphone it does this. On two different phones and two different accounts. Try for yourself and I'm sure it will do exactly the same thing unless uploading them to this page has changed them in some way.
    I used illustrator cs6 to make the blue shirt image. The other three were files sent from a customer.
    Thanks
    hub-international-pennington-AQUATIC-BLUE-tee-2014.jpg
    LOS.jpg
    G&B.jpg
    BroussrdDavid.jpg
    The following is what comes out the other side.
    This one got renamed to image002.jpg somewhere through the email program.
    The other three didn't change file names.
    Thanks for any help!

    This may depend on your chosen encoding options for the Mails (MIME vs. Base64 or similar) and/or the mails being reduced in size and sliced up server side. Apple (and Google) do stuff like recompressing images when viewing mails on mobile devices from an Apple ID or Gmail account... You have to turn it off in their web frontends....
    Mylenium

  • While trying to purchase a gift card to send via email, got a message this apple ID not eligible for purchase.  I've purchased many times before and this has never happened.  Does anyone know why?

    While trying to purchase a gift card to send via email, got a message this apple ID not eligible for purchase.  I've purchased many times before and this has never happened.  Does anyone know why?

    Re: ITunes will not let me send a gift certificate...Error message says: This Apple ID is not currently eligible to purchase gift certificates. I have a valid Apple ID so please tell me why this is happening if you know.
    iTunes Customer Service Contact - http://www.apple.com/support/itunes/contact.html
    Are you still using OSX 10.4.11? I thought the Store didn't work with Tiger.

Maybe you are looking for