Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JPanel, getGraphics and NPE problems.

807601Mar 30 2008 — edited Apr 5 2008
I've been having a problem with the getGraphics() method in my code throwing Null Pointer Exceptions, as early on in the code graphics are taken from an image and loaded into a variable, and as there are currently no graphics in the image, getGraphics() returns null. Of course, when I try to run this, Java doesn't like it.

public class myPanel extends JPanel
{
	private Image img;
	private Graphics g1;

	public myPanel() { // all instances must be prepared
		x1 = 300;
		y1 = 300;
		img = createImage(x1, y1); 		
		g1 = img.getGraphics();	
		run();
	}

	public void run() {
		makeGraphics();
	}

	public void paint(Graphics g) {
		update(g); 
	}
	
	public void update(Graphics g) {
		g.drawImage(img, 0, 0, this);
	}
	
	private void makeGraphics() { 
		int x, y;
			
		for (x = 0; x < x1; x++) {
			for (y = 0; y < y1; y++) {
				g1.drawLine(x, y, x + 1, y);			
			}
		}
	}
	
}
This is a completely stripped down version of the code, so don't worry if it looks a bit pointless. I'm just wondering if there is a way to get round this getGraphics() problem? I read an article yesterday which said not to use it at all!

Looking at the code myself, I don't totally understand how the g1 image gets painted, and because I'm converting this from an Applet to a JPanel I'm not entirely sure if the methods run in the correct order.

I understand Applets have init(), start(), stop() and destroy() methods. What would be the JPanel equivalent of these, and when do these methods run?

Thanks for any help you can give.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 3 2008
Added on Mar 30 2008
7 comments
807 views