国际象棋程序的线程“main”java.lang.NullPointerException中的异常

时间:2013-10-21 10:34:41

标签: java swing exception pointers awt

我正在尝试写一个4平方的国际象棋游戏。我想添加上,下,左,右,左上图,左上图,右图和右下图的按钮。在我尝试添加按钮后,它开始给我错误。

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

class chessGame extends JFrame implements ActionListener {
    JPanel p1, p2, p3, p4, buttons;
    JButton up, down, left, right, lud, ldd, rud, rdd;
    chessGame() {
        Container c = getContentPane();

        p1 = new JPanel();
        p1.setBackground(Color.black);
        p1.setOpaque(true);
        p1.setLocation(200,200);
        p1.setPreferredSize(new Dimension(90, 90));
        p2 = new JPanel();
        p2.setBackground(Color.white);
        p2.setOpaque(true);
        p2.setLocation(250,200);
        p2.setPreferredSize(new Dimension(90, 90));
        p3 = new JPanel();
        p3.setBackground(Color.white);
        p3.setOpaque(true);
        p3.setLocation(300,300);
        p3.setPreferredSize(new Dimension(90, 90));
        p4 = new JPanel();
        p4.setBackground(Color.black);
        p4.setOpaque(true);
        p4.setLocation(550,500);
        p4.setPreferredSize(new Dimension(90, 90));

        up = new JButton("UP");
        down = new JButton("DOWN");
        left = new JButton("LEFT");
        right = new JButton("RIGHT");
        lud = new JButton("LEFT UP DIAG.");
        ldd = new JButton("LEFT DOWN DIAG.");
        rud = new JButton("RIGHT UP DIAG.");
        rdd = new JButton("RIGHT DOWN DIAG.");

        buttons.add(up);
        buttons.add(down);
        buttons.add(left);
        buttons.add(right);
        buttons.add(lud);
        buttons.add(ldd);
        buttons.add(rud);
        buttons.add(rdd);
        c.add(p1);
        c.add(p2);
        c.add(p3);
        c.add(p4);
        c.add(buttons);
        c.setLayout(new FlowLayout());
        setVisible(true);
        setSize(200,400);
        setResizable(false);

    }

    public void actionPerformed(ActionEvent e) {

    }

    public static void main(String[] args) {
        chessGame output = new chessGame();
    }
}

1 个答案:

答案 0 :(得分:2)

您忘记初始化buttons小组

因此,在执行buttons.add(up);时会抛出NullPointerException

NullPointerException通常很容易被捕获。检查错误堆栈,我们将看到抛出哪个通道,因此可以检测到尚未初始化的通道。