Original Post
Sorry for such an elementary question. I'm attempting to code an aquarium "game" that is more like a hands-off simulation. I'm running into a problem with double buffering. When I try to createImage for the double buffer it returns a null. Hence when I try to get the Graphics context for the double buffer it throws a NullPointerException. I've looked hither and yon for the answer, googled, yahooed, searched archives and I can't seem to find exactly what I'm looking for. Here is the code. This is my panel class:
package aquarium;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.Toolkit;
import javax.swing.JPanel;
/**
*
* @author Rob
*/
public class TankPanel extends JPanel {
private MediaTracker mt;
private Image backGround;
private Image[] fishies;
private Image buffBackGround;
private Graphics buffGraphics;
private Rectangle borders;
/** Creates a new instance of TankPanel */
public TankPanel() {
super();
this.setLayout(null);
this.setDoubleBuffered(true);
fishies = new Image[2];
prepImage();
prepBufferedImage();
setPreferredSize(new Dimension(backGround.getWidth(this),
backGround.getHeight(this)));
borders = findBorders();
}
private void prepImage()
{
backGround = Toolkit.getDefaultToolkit().
getImage("F:\\ProjFiles\\NBWorkspace\\Aquarium\\data\\bubbles.gif");
fishies[0] = Toolkit.getDefaultToolkit().
getImage("F:\\ProjFiles\\NBWorkspace\\Aquarium\\data\\fish1.gif");
fishies[1] = Toolkit.getDefaultToolkit().
getImage("F:\\ProjFiles\\NBWorkspace\\Aquarium\\data\\fish2.gif");
mt = new MediaTracker(this);
mt.addImage(backGround,0);
mt.addImage(fishies[0],0);
mt.addImage(fishies[1],0);
try
{
mt.waitForAll();
}
catch (InterruptedException e){
System.err.println("Error loading picture");
}
repaint();
}
private void prepBufferedImage()
{
buffBackGround = createImage(getSize().width,
getSize().height);
if(buffBackGround == null)
{
System.out.println("Buffered Image is null");
}
else
{
buffGraphics = buffBackGround.getGraphics();
}
}
private Rectangle findBorders()
{
return new Rectangle(0 + getInsets().left,
0 + getInsets().top,
getSize().width - (getInsets().left + getInsets().right),
getSize().height - (getInsets().top + getInsets().bottom));
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension dim = this.getPreferredSize();
g.drawImage(backGround,0,0,this);
}
} I can't seem to get a handle on this.