Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Graphics class NullPointerException Initialize Graphics Class??

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Graphics class NullPointerException Initialize Graphics Class??

    I am creating a program for my final in an AP computer science class. My idea was simple: create a program that drops "meteors" and you have to dodge them with your mouse. I wrote the whole program, and then ran it and got a NullPointerException, because I did not use the Graphics class right or something. I am a good programmer, but I am not familiar at all with graphics of any kind, and the Graphics class looked easy to use, but I am not very good at it. I am trying to stay away from the JPanel/ javax.swing because I have absolutely no idea how to use them. Please help me.
    (Note: Code is commented and pretty self explanatory)
    Attached Files Attached Files


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    got a NullPointerException
    Can you post the full text of the error message and the code that goes with it.
    I prefer NOT to down load .doc files.
    Post the code so it can be easily read.

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    Very few (if any) will download attachments - I recommend you post the code into the forum itself (be sure to use the code tags). For what its worth, I'm betting you are doing the painting incorrect based upon the following comment:
    I am trying to stay away from the JPanel/ javax.swing because I have absolutely no idea how to use them
    JPanel's are made for painting - and simply override the paintComponent and use the Graphics class passed might solve your problems.
    See http://download.oracle.com/javase/tu...wing/painting/

  4. The Following User Says Thank You to copeg For This Useful Post:

    bglueck (May 13th, 2011)

  5. #4
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    //Meteor.java
    import java.applet.*;
    import java.awt.*;
    public class Meteor {
    	//Problem
    	Graphics g;
    	//Randomize x coordinate of meteor
    	private int randomNum = (int)(Math.random() * 250);
    	private int mRadius;
    	private int y = 0;
        private final int X = randomNum;
    	public Meteor(int radius, Graphics g){
    		mRadius = radius;
    		g.setColor(Color.white);
    		g.fillOval(randomNum, y, 2 * radius, 2 * radius);
    	}
    	public void fall(Graphics g){
    		//draw over old meteor
    		g.setColor(Color.black);
    		g.fillOval(randomNum, y, 2 * mRadius, 2 * mRadius);
    		//draw new meteor
    		g.setColor(Color.white);
    		y+=5;
    		g.fillOval(randomNum, y, 2 * mRadius, 2 * mRadius);
    	}
    	//Getters
    	public int getX() {
    		return X;
    	}
    	public int getY() {
    		return y;
    	}
    	//Test for if meteor is out of screen
    	public boolean isOutOfScreen(){
    		//250 is a random number I chose- its the applet windows length
    		if(this.getY() > 250){
    			return true;
    		}
    		else{
    			return false;
    		}
     
    	}
     
    }

    //Player.java
    import java.awt.*;
    import java.applet.Applet;
    import java.awt.Event;
    public class Player {
    	//Problem
    	Graphics g;
    	private int mouseXPosition, mouseYPosition;
    	public Player(Graphics g){
    		//get your mouse position and draw a red circle around it
    		mouseXPosition = getMousePositionX();
    		mouseYPosition = getMousePositionY();
    		g.setColor(Color.red);
    		g.fillOval(mouseXPosition,mouseYPosition, 20, 20);
    	}
    	public int getMousePositionX() {
    		PointerInfo a = MouseInfo.getPointerInfo();
            Point b = a.getLocation();
            int x = (int) b.getX();
            return x;
    	}
    	public int getMousePositionY() {
    		PointerInfo a = MouseInfo.getPointerInfo();
            Point b = a.getLocation();
            int y = (int) b.getY();
            return y;
    	}
    	//updates where the circle around your mouse is
    	public boolean mouseMove(Event e, int x, int y, Graphics g){
    		if (getMousePositionX() != mouseXPosition || getMousePositionY() != mouseYPosition){
    			g.setColor(Color.black);
    			g.fillOval(mouseXPosition,mouseYPosition, 20, 20);
    			mouseXPosition = getMousePositionX();
    			mouseYPosition = getMousePositionY();
    			g.setColor(Color.red);
    			g.fillOval(mouseXPosition,mouseYPosition, 20, 20);
    			return true;
    		}
    		else{
    			return false;
    		}
     
    	}
    }

    //World.java
    import java.applet.*;
    import java.awt.*;
    public class World {
    	Graphics g;
    	Meteor meteor = new Meteor(10, g);
    	Player player = new Player(g); 
    	boolean isCollide;
    	private int score = 0;
    	//////////////////////////////////
    	//Test for Collision//////////////
    	/////////////////////////////////
    	public boolean collision(){
    		int pX = player.getMousePositionX();
    		int pY = player.getMousePositionY();
    		int mX = meteor.getX();
    		int mY = meteor.getY();
    		if(pX > mX - 5 && pX < mX + 5){
    			if(pY > mY - 5 && pY < mY + 5){
    				isCollide = true;
    			}
    		}
    		else{
    			isCollide = false;
    		}
    		return isCollide;
    	}
    	////////////////////////
    	//Increment score by 10
    	////////////////////////
    	public void scoreAdd(){
    		if (!(collision())){
    			score += 10;
    		}
    		else{
    			score = score;
    		}
    	}
    	///////////////////////
    	public int getScore(){
    		return score;
    	}
     
    }

    //MeteorDodger.java
    //Driver Class
    import java.awt.*;
    import java.applet.*;
    import java.util.ArrayList;
    public class MeteorDodger extends Applet{
    	Graphics g;
    	static Event e;
        public void init(){
        	g.setBackground(Color.black);
        }
        public void paint(Graphics g){
        	Player player = new Player(g);
    		World world = null;
    		g.drawString("Score: " + world.getScore(), 0, 500);
        }
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Graphics g;
    		//attempt to innitialize???
    		g = g.getGraphics();
    		Player player = new Player(g);
    		World world = null;
    		ArrayList<Meteor> listMeteors = new ArrayList<Meteor>();
    		while (!(world.collision())){
    			listMeteors.add(new Meteor(10,g));
    			for(int i = 0; i < listMeteors.size(); i++){
    				listMeteors.get(i).fall(g);
    				if((listMeteors.get(i).isOutOfScreen())){
    					listMeteors.remove(i);
    				}
    			}
    			world.scoreAdd();
    			//Disregard. not completed yet: test for is mouse move
    			if((player.mouseMove(e, player.getMousePositionX(), player.getMousePositionY(), g))){
    				player.mouseMove(e, player.getMousePositionX(), player.getMousePositionY(), g);
    			}
    		}
    	}
     
    }

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    Where is the text of the error message?

    Is you program supposed to be an Applet that runs in a browser or does it run from a commmand line? I see a main method and a class that extends the Applet class.
    Last edited by Norm; May 13th, 2011 at 05:49 PM.

  7. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    And to add to Norm's questions, I also see the following:
    Graphics g;
    	Meteor meteor = new Meteor(10, g);
    	Player player = new Player(g);
    Object variables that are not initialized are by default null...g is never initialized. Override the paintComponent method of a JPanel - its much easier and the proper way to draw. Here is an example:
    public class MyPanel extends JPanel{
        @Override
        public void paintComponent(Graphics g){
            //do your drawing here. 
        }
    }

    Your above code will have to be refactored a bit, but not too much.

  8. #7
    Junior Member
    Join Date
    May 2011
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    thank you so much copeg. ill add that. will I need to take all the drawOval calls out of the various constructors and put them in that override or can they remain there, just slightly altered? if the latter is true, will I have to incorporate some sort of JPanel code to the fillOval? what will be the new call if so?

  9. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Graphics class NullPointerException Initialize Graphics Class??

    Quote Originally Posted by bglueck View Post
    thank you so much copeg. ill add that. will I need to take all the drawOval calls out of the various constructors and put them in that override or can they remain there, just slightly altered? if the latter is true, will I have to incorporate some sort of JPanel code to the fillOval? what will be the new call if so?
    My advice would be to think "object oriented programming". Each object has its purpose, and to separate each object based upon that purpose. For example, you have defined classes (World, Meteor, etc..) and could then have classes which define how these are drawn (JPanel(s), etc..). As an pseudo-example
    public class MyPanel extends JPanel{
     
        private Meteor meteor;
        private World world;
        public MyPanel(Meteor m, World w){
            meteor = m;
            world = w;
        }
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawOval(..get meteor values....);
            ....etc....
        }
    }

    You could also place draw methods in your classes, which you can pass a Graphics object to and can be called from the paintComponent...many ways to go about it.

Similar Threads

  1. Help with Graphics class and keyPressed method
    By smashX in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 10th, 2011, 12:46 PM
  2. paintComponent(Graphics g)
    By Kumarrrr in forum Java Theory & Questions
    Replies: 1
    Last Post: February 8th, 2011, 08:55 AM
  3. Help about Graphics
    By mamech in forum What's Wrong With My Code?
    Replies: 13
    Last Post: September 9th, 2010, 03:20 PM
  4. Graphics mayhem
    By javapenguin in forum AWT / Java Swing
    Replies: 2
    Last Post: August 9th, 2010, 05:21 PM
  5. graphics in job?
    By SweetyStacey in forum The Cafe
    Replies: 10
    Last Post: May 3rd, 2010, 03:29 PM