0

I was following a tutorial on making a simple game with Java, but for some reason my code stopped working for no reason that I can find. This is Window class that I was using.

    package com.tutorial.main;

    import java.awt.Canvas;
    import java.awt.Dimension;

    import javax.swing.JFrame;

    public class Window extends Canvas{

        private static final long serialVersionUID = -240840600533728354L;

        public Window(int width, int height, String title, Game game){
            JFrame frame = new JFrame(title); // line 13

            frame.setPreferredSize(new Dimension(width,height));
            frame.setMaximumSize(new Dimension(width,height));
            frame.setMinimumSize(new Dimension(width,height));

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.add(game);
            frame.setVisible(true);
            game.start();

        }
    }

Yesterday it worked fine. Today, when I reopened Eclipse, added some more code and tried running it I get a NullPointer Exception.

    Exception in thread "main" java.lang.NullPointerException
        at java.awt.Window.init(Window.java:497)
        at java.awt.Window.<init>(Window.java:537)
        at java.awt.Frame.<init>(Frame.java:420)
        at javax.swing.JFrame.<init>(JFrame.java:233)
        at com.tutorial.main.Window.<init>(Window.java:13)
        at com.tutorial.main.Game.<init>(Game.java:26)
        at com.tutorial.main.Game.main(Game.java:105)

I did not change anything in the Window class, nor the game class so I have no idea what is causing this. This is the line in Game.java that calls the window:

    new Window(WIDTH, HEIGHT, "Game", this); // line 26
  • 1
    Rename your class asap. You've got a name clash going on that is bad, very bad. – Hovercraft Full Of Eels Apr 08 '16 at 00:21
  • As for your NPE, the heuristic for NullPointerExceptions is almost always the same: You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. – Hovercraft Full Of Eels Apr 08 '16 at 00:23
  • If you're still stuck, then create and post your [mcve] that reproduces your problem. – Hovercraft Full Of Eels Apr 08 '16 at 00:26
  • I just restarted my computer and now it is working. I didn't change anything so it seems to have been an issue outside of the code. – Whatsisface Apr 08 '16 at 00:29

0 Answers0