Search code examples
javaswingjframegraphics2d

Java - double buffering NullPointerException


I'm writing a simple game. I have 3 classes the first one: ball which take care of every thing refereed to it, the second one game which made out of an array of "ball"s and the final one is windows, the one which contains the MAIN thread.

window.paint calls game.draw in order to receive the graphics of the game scene.While the game itself double buffering it in order that the Image object can be moved to the Player's ball location(yet to be implemented).

So my problem caused because I'm creating an Image object but somewhy this initialized to null, thus I get NullPointerException.

Here is the source of the methods which handle the painting:

public class MyWindow extends JFrame {
        //...the other code
        public void paint(Graphics g){
            thegame.draw();
            repaint();
        }
}

public class Game extends JFrame implements Runnable {
    ball[] cellmap;

    //...the other code

    public void draw(){
        Image GameImage = createImage(800,800);
        Graphics GameGraphics = GameImage.getGraphics();

        for(int i = 0;i<cellmap.length;i++)
            cellmap[i].draw(GameGraphics);

        g.drawImage(GameImage, 0, 0, this); 
    }
}

public class Ball extends JFrame {
        //...the other code
    public void draw(Graphics g){
        g.setColor(Color.red);
        g.fillOval((int)(this.x+this.radious),(int)(this.y+this.radious),
                       (int)this.radious,(int)this.radious);        
    }
}

Solution

  • 1) please read Java Naming Conventions

    2) not good idea paint directly to the JFrame, put your painting to the JComponent, JLabel, JPanel

    3) for Painting in Swing use method paintComponent, please not methods paint(Graphics g) or draw(Graphics g)

    4) if you want to delay or animate you painting use javax.swing.Timer