Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 每个循环中的数组错误_Java_Arrays_Swing_Jbutton - Fatal编程技术网

Java 每个循环中的数组错误

Java 每个循环中的数组错误,java,arrays,swing,jbutton,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 =

我正在为一个带有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++;
        }       
    }   
}
Java中的对象默认为空。对象数组中的对象也不例外。您需要先初始化JButton数组letterbutton,然后再尝试对其调用任何操作

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

JButton[]letterbutton=新JButton[26];将每个数组元素初始化为null。您必须在数组中循环,并为每个位置分配一个新的JButton

谢谢您的帮助!我很感激!