1

Following on from my previous questions about this concentrate game i have been working on i have hit a java.lang.NullPointerException when trying to run a specific part of it and i cannot find out what could be causing it, It just appears to be pointing to my main method in netbeans.

Exception in thread "main" java.lang.NullPointerException
    at concentrate.Concentrate.main(Concentrate.java:281)

Here is the code or the page that the error is appearing on, at first i thought it may be something to do with my playGame method i was running but nothing appeared to change. Even when i removed everything from within it so once again i have come to stack overflow for help.

package concentrate;
import static concentrate.HighscoreManager.scores;
import static concentrate.Score.nameField;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.logging.Logger;
import javax.swing.*;


public final class Concentrate extends JFrame implements ActionListener {  
    //below are all the variables declared for the gui and the game program itself

    private final JFrame window = new JFrame("Concentrate");
    private  final int WINDOW_WIDTH = 330; 
    private  final int WINDOW_HEIGHT = 485; 
    private JButton exitBtn, scoresBtn, resetButton;  
    public static ArrayList<Card> gameBtn;
    public static int Point = 46;
    public static int numCards = 16;
    public static JLabel Score;  
    public static GameButtonPanel gamePnl;
    private final Panel buttonPnl = new Panel();   
    private final Panel scorePnl = new Panel(); 
    private GameButtonListener buttonListener; // Listener for the button actions
    private GameButtonPanel gui;           // The GUI this game controls
    Concentrate game;


    Random rand = new Random();
    private int cardVal;
    private GameButtonPanel theGUI;

    //update score checks and sets the score on the main board 
    public static void updateScore() {
        Score.setText("Score: " + Point);

    }





    public Concentrate(){ 
        //below is calling the create gui function and set variables for it width and close operation
        createGUI();  
        createpanels(); 

        window.setTitle("Concentrate"); 
        window.setDefaultCloseOperation(EXIT_ON_CLOSE); 
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); 
        window.setVisible(true);
        shuffleButtons();

        gui = theGUI;

        gamePnl = new GameButtonPanel();
        game = gamePnl.game;

        buttonListener = new GameButtonListener();

        // Adds each button to the actions listener
        for(Card c : gameBtn)
            c.addActionListener(buttonListener);
    }

    //createpanels sets diffrent panels within windows to add the buttons and score on organised from top, main and bottom
    public void createpanels()
    {
        /*gameBtn = new ArrayList<>(numCards * 2);*/
        gameBtn = new ArrayList<>(numCards);
        gamePnl = new GameButtonPanel(shuffleButtons());

        //below adds the cards to the panel based on the number of them
        for(int i = 0; i < numCards; i++)
        {
            Card cb = new Card(i);
            gameBtn.add(cb); 
        }

        buttonPnl.add(scoresBtn); 
        buttonPnl.add(exitBtn);
        buttonPnl.add(resetButton);
        gamePnl.setLayout(new GridLayout(4, 4)); 

        buttonPnl.setLayout(new GridLayout(1, 0));
        scorePnl.add(Score);
        scorePnl.setLayout(new GridLayout(1, 0));
        window.add(scorePnl, BorderLayout.NORTH);
        window.add(gamePnl, BorderLayout.CENTER);
        window.add(buttonPnl, BorderLayout.SOUTH);
    }  

    public void createGUI() {  
        buttonListener = new GameButtonListener();
        Score = new JLabel("Score: " + Point);
        exitBtn = new JButton("Exit"); 
        exitBtn.addActionListener(this);
        scoresBtn = new JButton("Leaderboard");  
        scoresBtn.addActionListener(this);
        resetButton = new JButton("Reset"); 
        resetButton.addActionListener(this);
    }   

    public static ArrayList<Card> shuffleButtons() {
        Collections.shuffle(Arrays.asList(gameBtn));

        layoutButtons();
        return gameBtn;
    }

    public static void layoutButtons() {
        for (JButton button : gameBtn) {
            gamePnl.add(button);
        }
    }
    //the code below is for the lower menu buttons
    @Override
    public void actionPerformed(ActionEvent e) 
    {    
            //this is the exit button displayed onthe bottomof the gui
            if (exitBtn == e.getSource()) 
            { 
                System.exit(0);
            } 
            //this is the button at the botto of the gui which calls on the leaderboard frame
            if (scoresBtn == e.getSource()) 
            {     
                new Leaderboard().setVisible(true);
            }    
            if (resetButton == e.getSource()) 
            {     
                shuffleButtons();
            } 
    } 

    public void reset()
    {
        // Unhide all the card buttons and set them face down
        for(Card cb : gameBtn)
        {
            cb.setFaceDown();
            cb.setVisible(true);
        }
    }

    public void playGame(){
        int PairsFound;
        int stillPlaying;
        JButton buttonPressed;
        Card button1, button2; 

        stillPlaying = JOptionPane.YES_OPTION;

        while(stillPlaying == JOptionPane.YES_OPTION)
        {
            PairsFound = 0;
            buttonPressed = null;
            // Loop until all the cards are matched.

            while(PairsFound != cardVal / 2){

                // Wait for first card to be pressed
                buttonPressed = buttonListener.waitForButton();

                if(buttonPressed instanceof Card)
                {
                    button1 = (Card)buttonPressed;
                    button1.setFaceUp();
                }
                else
                {
                    if(buttonPressed.getActionCommand().equals(gameBtn))
                        System.out.println("button was"+ gameBtn +"pressed");
                    break;
                }

                // Wait for second card to be pressed
                buttonPressed = buttonListener.waitForButton();

                if(buttonPressed instanceof Card)
                {
                    button2 = (Card)buttonPressed;
                    button2.setFaceUp();
                }
                else
                {
                    if(buttonPressed.getActionCommand().equals(exitBtn))
                        stillPlaying = JOptionPane.NO_OPTION;
                    break;
                }

                // Unflip the cards if they are not equals or if they are the
                // same card (if they refer to the same object)
                if(!button1.equals(button2) || button1 == button2){
                    ((Card)button1).setFaceDown();
                    ((Card)button2).setFaceDown();
                    Point = Point - 1;
                }
                else
                {
                    button1.setVisible(false); // Hide the pair once found.
                    button2.setVisible(false);
                    PairsFound++;
                }

                // If found all matching pairs.
                if(PairsFound == cardVal / 2)
                {

                }
            }
        }
    }

    private static final Logger LOG = Logger.getLogger(Concentrate.class.getName());

    public static void main(String[] args)
    {  
        Concentrate concentrate = new Concentrate(); 
        concentrate.game.playGame();
    }
}

Sorry if my code is a mess still pretty new to java, still learning any help would be appreciated thank you.

I wouldn't say this is a duplicate question as i did not ask what a null pointer was specifically i asked what is causing it to be thrown within my java program but maybe i am wrong i dont remember asking exactly what it was a NullPointerException was.

Aidan Doherty
  • 962
  • 2
  • 11
  • 29
  • 1
    check line 281. which variable is null? check where it is/should be instantiated. add a check whether it is null or not, if it is, don't call a method on it or pass it as parameter, otherwise, complete the flow – Stultuske May 23 '14 at 14:00
  • thats the problem i am having line 281 is the main method concentrate.game.playGame(); – Aidan Doherty May 23 '14 at 14:02
  • "the main method" is stretched over 5 lines. which line is it? – Stultuske May 23 '14 at 14:02
  • 1
    `concentrate.game` is null. Trace your code to figure out why that's the case. – Mat May 23 '14 at 14:02
  • probably. but since that 'game' variable is retrieved from a class of which the code isn't show, Aidan 'll have to look further in that class. – Stultuske May 23 '14 at 14:04
  • the concentrate method is working fine as the gui display for it with no trace errors appearing when its run alone. But "game" is the panel in which the cards are displayed on to match with each other which i am trying to get my playGame method to work on. – Aidan Doherty May 23 '14 at 14:05
  • 1
    This one is difficult to answer without further classes to explore. I would suggest you put a breakpoint on the given line of the error, start debug mode, and check which object is null. Then you just need to trace it back until you go "oooh!" There might come a day where you will appreciate the simplicity of NullPointerExceptions :). They are at least very specific compared to a lot of other errors. Good luck, and continue playing :) – jumps4fun May 23 '14 at 14:15
  • @KjetilNordin thanks for that have been enjoying this project have found out a fair bit about java doing it but its starting to overcome me know a but. But I will finish it :D – Aidan Doherty May 23 '14 at 14:18
  • running it in debug mode i inserted a breakpoint under game = gamePnl.game; when it reaches the instance of this in my main class the debugger shows "Debugger stopped on uncompilable source code." – Aidan Doherty May 23 '14 at 14:30
  • I fail to see how this is a duplicate of that question i never asked what a NullPointerException, I asked if anyone knew how it was being thrown within the main method of my program without no other trace of where it was coming from, It was solved through suggestions from @KjetilNordin and Warren Dew telling me to debug it and what could mainly be the cause, So i debugged it and found out it was the game class that was causing it and so then i removed it and alternated it so it could run my playGame() function. Then created the game panel directly within the concentrate class. – Aidan Doherty May 23 '14 at 17:18

2 Answers2

1

Apparently the null pointer exception is coming from this line:

concentrate.game.playGame();

You know concentrate isn't null, since you just constructed it successfully; if it hadn't been constructed successfully, an exception would be thrown from the concentrate constructor and this line wouldn't be reached. That means it's game that's null.

Now we go back to the Concentrate constructor and look at where game is initialized. It appears to be initialized in the following line:

game = gamePnl.game;

You don't show the constructor for gamePnl, but the conclusion is that the GamePanel constructor fails to initialize it's own game member, so that member is null and concentrate.game also ends up being null.

You will probably need to refactor the code to create either the concentrate game, or the game panel, first, then pass one to the constructor of the other. As it is, they seem to each refer to the other, which is a difficult situation to set up properly.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
0

I don't know if this is the problem but you have a line: gui = theGUI;

I can't find any place in your code where the variable theGUI is instalised.

Robert3452
  • 1,354
  • 2
  • 17
  • 39
  • oops that was something i was trying a while ago but it does not seem to be what was causing the problem still getting the same error – Aidan Doherty May 23 '14 at 14:11