每个循环java中的数组错误

时间:2013-05-11 02:28:38

标签: java arrays swing jbutton

我正在研究具有swing UI的基本刽子手游戏的代码。我正在使用for循环来启动字母的所有按钮。但是我在第39行得到一个空指针异常。我已经查看了它并且不确定为什么它不能正常工作。最底层的10行代码是问题被抛出。

    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 个答案:

答案 0 :(得分:7)

默认情况下,Java中的对象为nullObject数组中的数据没有什么不同。您需要在尝试调用JButton数组letterButtons之前初始化它们

for (int i=0; i < letterButtons.length; i++) {
   letterButtons[i] = new JButton();
}

答案 1 :(得分:3)

JButton[] letterButtons = new JButton[26];将每个数组元素初始化为null。您必须遍历数组并为每个位置分配new JButton()