Graphics throwing NullPointerException when running drawImage()

I've tried a few too many ways to repeatedly draw an image, and I know that using Graphics is better than initializing 500+ JLabels just to draw 1x100 images as a toolbar.

This code keeps throwing NullPointerExceptions and I simply can't figure out why. Maybe someone a bit more insightful than myself knows what I did wrong?

privatevoid addGUIComponents(JFrame jf){

JPanel btmbar =new JPanel();

btmbar.setBounds(0, jf.getHeight() - 100, jf.getWidth(), 150);

btmbar.setLayout(null);

//add the toolbar

for (int i = 0; i < jf.getWidth(); i++){

try{

BufferedImage img = ImageIO.read(new File("images/btm-bar.png"));// 1x100 image

Graphics g = btmbar.getGraphics();

g.drawImage(img,i, i, btmbar);

}catch (Exception e){

e.printStackTrace();

}

}

jf.getContentPane().add(btmbar);

}

That code throws the following for each time I try drawing the image:

java.lang.NullPointerException

at eyecandy1.gui.addGUIComponents(gui.java:67)

at eyecandy1.gui.<init>(gui.java:49)

at eyecandy1.gui.main(gui.java:77)

[1741 byte] By [timothyb89_a] at [2007-11-27 11:19:20]
# 1

getGraphics always returns null until the component you are calling it on is realized.

It has a valid graphics context when/after it first appears.

// Load image once and save a reference to it.

BufferedImage img = null;

try {

img = ImageIO.read(new File("images/btm-bar.png")); // 1x100 image

} catch (IOException e) {

System.out.println(e.getMessage());

}

//add the toolbar

JPanel btmbar = new JPanel() {

protected void paintComponent(Graphics g) {

super.paintComponent(g);

for (int i = 0; i < jf.getWidth(); i++) {

Graphics g = btmbar.getGraphics();

g.drawImage(img,i, i, this);

}

}

};

btmbar.setBounds(0, jf.getHeight() - 100, jf.getWidth(), 150);

btmbar.setLayout(null);

jf.getContentPane().add(btmbar);

crwooda at 2007-7-29 14:36:09 > top of Java-index,Security,Cryptography...