0

我正在尝试编写一个 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();
    }
}
4

1 回答 1

2

你忘了初始化你的buttons面板

因此,当这样做buttons.add(up);时会抛出一个NullPointerException.

NullPointerException通常很容易被抓住。检查错误堆栈,我们将看到这是在哪个通道上抛出的,因此可以检测到未初始化的内容。

于 2013-10-21T10:35:42.010 回答