Graphics error

I am trying to draw a photograph in a JFrame with some other information. I set up and load the Image and draw it to a buffered image. When I go and get the graphics from the panel I want to draw to, I get null back. My code look like:

backbuffer =new BufferedImage(photoPanel.getWidth(), photoPanel.getHeight(), BufferedImage.TYPE_INT_RGB);

g2 = backbuffer.createGraphics();

try{

photo = tk.getImage(photopath);

}catch (Exception e){

photo = tk.getImage("images/null.png");

}

g2.drawImage(photo, 0, 0, photoPanel.getWidth(), photoPanel.getHeight(),null);

if (photoPanel.getGraphics() ==null){

System.out.println("Null Graphics");

}else{

photoPanel.getGraphics().drawImage(backbuffer,640,20,200,200,this);

}

Both the JPanel (photoPanel) and JFrame return nothing. This is the first time I have run into a problem like this. The class file I am writing extends JFrame and the JPanel is a local variable.

I am using Java 1.6 and Net Beans 5.5

[1568 byte] By [Sideina] at [2007-11-27 8:18:01]
# 1

If the gui is not realized then none of the components such as JFrame and JPanel will have a

non–null graphics context. Using getGraphics is a con anyway. Use a JPanel and

override paintComponent for proper drawing.

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class FrameExtension extends JFrame {

BufferedImage backbuffer;

BufferedImage photo;

public FrameExtension() {

loadImage();

getContentPane().add(photoPanel);

setSize(400,400);

System.out.println("graphics context before realization = " +

photoPanel.getGraphics());

setVisible(true);

System.out.println("graphics context after realization = " +

photoPanel.getGraphics());

}

private void loadImage() {

String photopath = "images/cougar.jpg";

boolean groping = true;

while(groping) {

try {

photo = ImageIO.read(new File(photopath));

groping = false;

} catch (Exception e) {

System.out.println("Load error: " + e.getClass().getName() +

" " + e.getMessage());

if(photopath.equals("images/null.png"))

groping = false;

photopath = "images/null.png";

}

}

}

JPanel photoPanel = new JPanel() {

protected void paintComponent(Graphics g) {

if(backbuffer == null) {

backbuffer = new BufferedImage(getWidth(), getHeight(),

BufferedImage.TYPE_INT_RGB);

Graphics2D g2 = backbuffer.createGraphics();

g2.setBackground(getBackground());

g2.clearRect(0, 0, getWidth(), getHeight());

g2.drawImage(photo, 0, 0, null);

g2.dispose();

}

g.drawImage(backbuffer,0,0,this);

}

};

public static void main(String[] args) {

new FrameExtension();

}

}

crwooda at 2007-7-12 20:03:28 > top of Java-index,Security,Cryptography...
# 2
Thank you, I have it working now.
Sideina at 2007-7-12 20:03:28 > top of Java-index,Security,Cryptography...