在java中设置jLabel文本会抛出异常

2 java swing jlabel

我正在用Java实现Tic Tac Toe游戏,但是当我运行程序并按下按钮时,由于我的点击方法而发生了激活.不知何故,似乎JLabel从未被初始化.为什么?

package piskvorky;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Piskvorky extends JFrame {
    String[] tahy = {"O", "X"};
    int tah = 0;
    JButton[][] buttons;
    JLabel stav;
    int x, y;

    public Piskvorky(int x, int y) {
        this.x = x;
        this.y = y;

        setTitle("Piskvorky");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setLayout(new GridLayout(x, y+1));

        JButton[][] buttons = new JButton[x][y];

        for (int i = 0; i < x; ++i) {
            for (int j = 0; j < y; ++j) {
                buttons[i][j] = new JButton();
                buttons[i][j].setPreferredSize(new Dimension(50, 50));
                buttons[i][j].addActionListener(new MyTextListener());
                add(buttons[i][j]);
            }
        }

        JLabel stav = new JLabel();
        add(stav);

        pack();
    }

    class MyTextListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            JButton kliknute = (JButton) e.getSource();
            setProperties(kliknute);
        }
    };

    private void setProperties(JButton source)
    {
        source.setText(tahy[tah]);
        source.setEnabled(false);
        tah = 1-tah;
        if(tah == 0)
            stav.setText("Current player: o");
        else
            stav.setText("Current player: x");
    }

    public static void main(String[] args) {
        new Piskvorky(10, 10).setVisible(true);
    }

}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 7

您通过在构造函数中重新声明它来隐藏stav变量,所以是的,stav类字段为null.解决方案:确定,在构造函数中初始化stav但不要在那里重新声明它.

编辑:根据imxylz的评论,你也会影响其他变量.是时候学习变量阴影了.请查看关于此文章或Google文章的维基百科文章,因为这是了解和学习如何避免的重要概念.