0

im working on code for a basic hangman game with a swing UI. i am using a for loop to initiate all the buttons for the letters. however im getting a null pointer exception on line 39. I have looked it over and am not sure why it is not working properly. The bottom 10 or so lines of code is were the problem is being thrown.

    import java.awt.Color;
    import javax.swing.*;

    public class GameUI {

    public static void main(String[] args){
        GameUI ui = new GameUI();
        ui.initializeUI();
    }

    public void initializeUI(){
        //initialize the window
        JFrame window = new JFrame();
        window.setSize(500,500);
        window.setResizable(false);
        window.setVisible(true);

        //initialize main panel
        JPanel wrapper = new JPanel();
        wrapper.setLayout(null);
        Color BGColor = new Color(240,230,140);
        wrapper.setBackground(BGColor);
        window.getContentPane().add(wrapper);

        //Creates JLAbel title, this is used for the title of the game
        JLabel title = new JLabel("Hangman v0.1");
        title.setBounds(10, 5, 200, 50);
        wrapper.add(title);
        //=================================================================
        //Creates JButtons for each letter (ERROR OCCURS BELLOW ON FIRST LINE AFTER LOOP BEIGNS)
        //=================================================================
        char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        JButton[] letterButtons = new JButton[26];

        int counter = 0;

        for (char letter:alphabet){
            letterButtons[counter].setText("" + letter);

            //sets positions for each button
            int posY = 50;
            int posX = counter*5 + 10;
            letterButtons[counter].setBounds(posX, posY, 10, 10);
            wrapper.add(letterButtons[counter]);
            counter++;
        }       
    }   
}

2 Answers 2

7

Objects in Java are null by default. Those in an Object array are no different. You need to initialise your JButton array letterButtons prior to attempting to invoke any operations on them

for (int i=0; i < letterButtons.length; i++) {
   letterButtons[i] = new JButton();
}
Sign up to request clarification or add additional context in comments.

Comments

3

JButton[] letterButtons = new JButton[26]; initializes each array element to null. You have to loop through the array and assign each position a new JButton()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.