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 5 of 5

Thread: Not sure what is wrong with this code?? Please help

  1. #1
    Member
    Join Date
    Oct 2012
    Posts
    68
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Not sure what is wrong with this code?? Please help

    I am learning java from videos online, I wont post the link because i'm not sure if I would be allows but I can do if anybody wants.

    From the video I have copied the code exactly. My code compiles but when I run it, it doesn't work. The person online runs his and it works. No idea what's wrong:

    I am using practicing using sprites:

    Sprite class:
    import java.awt.Image;
     
    public class Sprite {
     
        private Animation a;
        private float x;
        private float y;
        private float vx;
        private float vy;
     
        //Constructor    
        public Sprite(Animation a)
        {
            this.a = a;
        }
     
        //Chnage position
        public void update(long timePassed)
        {
            x += vx * timePassed;
            y += vy * timePassed;
            a.update(timePassed);
        }
     
        //Get x position
        public float getX()
        {
            return x;
        }
     
        //Get y position
        public float getY()
        {
            return y;
        }
     
        //Set sprite x position
        public void setX(float x)
        {
            this.x = 0;
        }
     
        //Set sprite y position
        public void setY(float y)
        {
            this.y = 0;
        }
     
        //Get sprite width
        public int getWidth()
        {
            return a.getImage().getWidth(null);
        }
     
        //Get sprite height
        public int getHeight()
        {
            return a.getImage().getHeight(null);
        }
     
        //get horizontal velocity
        public float getVelocityX()
        {
            return vx;
        }
     
        //get vertical velocity
        public float getVelocityY()
        {
            return vy;
        }
     
        //set horizontal velocity
        public void setVelocityX(float vx)
        {
            this.vx = vx;
        }
     
        //set vertical velocity
        public void setVelocityY(float vy)
        {
            this.vy = vy;
        }
     
        //get sprite / image
        public Image getImage()
        {
            return a.getImage();
        }
     
    }

    Animation class:

    import java.awt.Image;
    import java.util.ArrayList;
     
    public class Animation{
     
        private ArrayList scenes;
        private int sceneIndex;
        private long movieTime;
        private long totalTime;
     
        //CONSTRUCTOR
        public Animation(){
            scenes = new ArrayList();
            totalTime = 0;
            start();
        }
     
        //Add scene to ArrayList and set time for each scene
        public synchronized void addScene(Image i, long t)
        {
            totalTime += t;
            scenes.add(new oneScene(i, totalTime));
        }
     
        //Start aimation from begining
        public synchronized void start()
        {
            movieTime = 0;
            sceneIndex = 0;
        }
     
        //Change scenes
        public synchronized void update(long timePassed)
        {
            if(scenes.size()>1){
                movieTime += timePassed;
                if(movieTime >= totalTime){
                    movieTime = 0;
                    sceneIndex = 0;
                }
                while(movieTime > getScene(sceneIndex).endTime){
                    sceneIndex++;
                }
            }
        }
     
        //get animations current scene AKA image
        public synchronized Image getImage()
        {
            if(scenes.size()==0){
                return null;
            }else{
                return getScene(sceneIndex).pic;
            }
        }
     
        //get scene
        private oneScene getScene(int x)
        {
            return (oneScene) scenes.get(x);
        }
     
        //Private inner class//
     
        private class oneScene{
            Image pic;
            long endTime;
     
            public oneScene(Image pic, long endTime)
            {
                this.pic = pic;
                this.endTime = endTime;
            }
        }
    }

    Screen Manager class:

     
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JFrame;
     
    public class ScreenManager {
     
        private GraphicsDevice vc;
     
        //Give vc acces to moniter screen
        public ScreenManager()
        {
            GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
            vc = e.getDefaultScreenDevice();
        }
     
        //Get all compatible display modes
        public DisplayMode[] getCompatibleDisaplyModes()
        {
            return vc.getDisplayModes();
        }
     
        //Compares display modes passed in to vc display modes and see if they match
        public DisplayMode findFirstCompatibleMode(DisplayMode modes[])
        {
            DisplayMode goodModes[] = vc.getDisplayModes();
            for(int x=0; x<modes.length; x++){
                for(int y = 0; y<goodModes.length; y++){
                    if(displayModesMatch(modes[x], goodModes[y])){
                        return modes[x];
                    }
                }
            }
            return null;
        }
     
        //Get current displayMode
        public DisplayMode getCurrentDisplayMode()
        {
            return vc.getDisplayMode();
        }
     
        //Checks if two modes match each other
        public boolean displayModesMatch(DisplayMode m1, DisplayMode m2)
        {
            if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight())
            {
                return false;
            }
            if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth())
            {
                return false;
            }
            if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate())
            {
                return false;
            }
     
            return true;
        }
     
        //Make frame full screen
        public void setFullScreen(DisplayMode dm)
        {
            JFrame f = new JFrame();
            f.setUndecorated(true);
            f.setIgnoreRepaint(true);
            f.setResizable(false);
            vc.setFullScreenWindow(f);
     
            if(dm != null && vc.isDisplayChangeSupported())
            {
                try{
                    vc.setDisplayMode(dm);
                }catch(Exception ex) {}
            }
     
            f.createBufferStrategy(2);
        }
     
        //Set graphics object = to this
        public Graphics2D getGraphics()
        {
            Window w = vc.getFullScreenWindow();
            if(w != null){
                BufferStrategy s = w.getBufferStrategy();
                return (Graphics2D)s.getDrawGraphics();
            } else{
                return null;
            }
        }
     
        //Updates display
        public void update()
        {
            Window w = vc.getFullScreenWindow();
            if(w != null){
                BufferStrategy s = w.getBufferStrategy();
                if(!s.contentsLost()){
                    s.show();
                }
            }
        }
     
        //Return full screen window
        public Window getFullScreenWindow()
        {
            return vc.getFullScreenWindow();
        }
     
        //Get width of window
        public int getWidth()
        {
            Window w = vc.getFullScreenWindow();
            if(w != null){
                return w.getWidth();
            }else{
                return 0;
            }
        }
     
        //Get hieght of window
        public int getHeight()
        {
            Window w = vc.getFullScreenWindow();
            if(w != null){
                return w.getHeight();
            }else{
                return 0;
            }
        }
     
        //Get out of full screen
        public void restoreScreen()
        {
            Window w = vc.getFullScreenWindow();
            if(w != null){
                w.dispose();
            }
            vc.setFullScreenWindow(null);
        }
     
        //Create image compatible with monitor
        public BufferedImage createCompatibleImage(int w, int h, int t)
        {
            Window win = vc.getFullScreenWindow();
            if(win != null){
                GraphicsConfiguration gc = win.getGraphicsConfiguration();
                return gc.createCompatibleImage(w,h,t);
            }
            return null;
        }
    }

    bucky class:

    import java.awt.*;
    import javax.swing.JFrame;
    import javax.swing.ImageIcon;
    import javax.swing.*;
     
    public class bucky2{
     
        public static void main(String args[]) {
            bucky2 b = new bucky2();
            b.run();
        }
     
        private Sprite sprite;
        private Animation a;
        private ScreenManager s;
        private Image bg;
        private static final DisplayMode modes1[] = {
            new DisplayMode(800,600,32,0),
            new DisplayMode(800,600,24,0),
            new DisplayMode(800,600,16,0),
            new DisplayMode(640,480,32,0),
            new DisplayMode(640,480,24,0),
            new DisplayMode(640,480,16,0),
        };
     
        //Load images and add scenes
        public void loadImages()
        {
            bg = new ImageIcon("C:\\temp\background1.jpg").getImage();
            Image face1 = new ImageIcon("C:\\temp\face1.png").getImage();
            Image face2 = new ImageIcon("C:\\temp\face2.png").getImage();
     
            a = new Animation();
            a.addScene(face1, 250);
            a.addScene(face2, 250);
     
            sprite = new Sprite(a);
            sprite.setVelocityX(0.3f);
            sprite.setVelocityY(0.3f);
        }
     
        //Main method called from main
        public void run()
        {
            s = new ScreenManager();
            try{
                DisplayMode dm = s.findFirstCompatibleMode(modes1);
                s.setFullScreen(dm);
                movieLoop();
            }finally{
                s.restoreScreen();
            }
        }
     
        //Play movie
        public void movieLoop()
        {
            long startingTime = System.currentTimeMillis();
            long cumTime = startingTime;
            while(cumTime - startingTime < 5000){
                long timePassed = System.currentTimeMillis() - cumTime;
                cumTime += timePassed;
                update(timePassed);
     
                //draw and update screen
                Graphics2D g = s.getGraphics();
                draw(g);
                g.dispose();
                s.update();
     
                try{
                    Thread.sleep(200);
                }catch (Exception ex){}
            }
        }
     
        //Draws graphics
        public void draw(Graphics g)
        {
            g.drawImage(bg, 0,0, null);
            g.drawImage(sprite.getImage(), Math.round(sprite.getX()), Math.round(sprite.getY()), null);        
        }
     
        //Update sprite positioning
        public void update(long timePassed)
        {
            if(sprite.getX() < 0){
                sprite.setVelocityX(Math.abs(sprite.getVelocityX()));
            }else if(sprite.getX() + sprite.getWidth() >= s.getWidth()){
                sprite.setVelocityX(-Math.abs(sprite.getVelocityX()));
            }
     
            if(sprite.getY() < 0){
                sprite.setVelocityY(Math.abs(sprite.getVelocityY()));
            }else if(sprite.getY() + sprite.getHeight() >= s.getHeight()){
                sprite.setVelocityY(-Math.abs(sprite.getVelocityY()));
            }
     
            sprite.update(timePassed);
        }
    }

    When I run my code, in the bucky class on the update method :
    public void update(long timePassed)
        {
            if(sprite.getX() < 0){

    That is what gives me a null pointer exception. I have tried many things but I can't think of anything.
    I have attached my code so if anybody wants to try it, I have done it in both blueJ and Eclipse.

    Sorry about the long code!

    Thank you.
    Attached Files Attached Files


  2. #2
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: Not sure what is wrong with this code?? Please help

    Exception in thread "main" java.lang.NullPointerException
    at bucky2.update(bucky2.java:87)
    at bucky2.movieLoop(bucky2.java:63)
    at bucky2.run(bucky2.java:49)
    at bucky2.main(bucky2.java:10)


    Screen goes black, but does nothing.

    Problem is here: if(sprite.getX() < 0){
    Last edited by Starstreak; October 20th, 2012 at 11:33 AM.

  3. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Not sure what is wrong with this code?? Please help

    Quote Originally Posted by sim18 View Post
    When I run my code, in the bucky class on the update method :
    public void update(long timePassed)
        {
            if(sprite.getX() < 0){

    That is what gives me a null pointer exception. I have tried many things but I can't think of anything.
    In bucky2 class you have a field named sprite, right? Where sprite is declared, it is a reference variable that is automatically given a null value, right?

    Well...
    1. Where is the sprite reference variable given a value other than null? (What method creates a Sprite object named sprite?)

    2. From where in the program is that method called?


    Cheers!

    Z
    Last edited by Zaphod_b; October 20th, 2012 at 01:33 PM.

  4. #4
    Member
    Join Date
    Oct 2012
    Posts
    68
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Not sure what is wrong with this code?? Please help

    The method loadImages gives sprite a value of a.

    Is my problem that loadImages in the bucky2 class is never called??

  5. #5
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Not sure what is wrong with this code?? Please help

    Quote Originally Posted by sim18 View Post
    Is my problem...?
    If that is the only place in the code where the sprite can be given a non-null value, and the NPE is generated because sprite has a null value when it is used, then I think you have found the reason for the NPE.

    Cheers!

    Z

Similar Threads

  1. What's wrong with my code
    By maronski in forum What's Wrong With My Code?
    Replies: 3
    Last Post: September 26th, 2012, 09:07 AM
  2. what is wrong with my code? need help
    By balmung123 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 1st, 2012, 04:12 AM
  3. What's Wrong With My Code?
    By Nuggets in forum What's Wrong With My Code?
    Replies: 11
    Last Post: January 31st, 2012, 10:11 PM
  4. what is wrong with my code?
    By bmb in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 7th, 2011, 09:03 AM
  5. What is wrong with my code???
    By nine05 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 8th, 2011, 09:59 AM