在actionevent中更改jlabel的文本

b4lqfgs4  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(399)

好的,我正在创建一个tic-tac-toe图形用户界面。我目前有一个3x3按钮的工作框架,将改变为一个x或o。我的问题是在按钮顶部实现jlabel。标签记录了轮到谁了,并且将从“o”或“x”改变,但是我似乎无法让jlabel更新(只会抛出错误)。下面是我的代码的一部分,展示了如何实现这一点。程序运行得很好,但只要我添加(turn.settext(“o's turn”);)我会出错。
任何关于为什么这可能不起作用的反馈都将不胜感激。

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

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

public class TicTacToe extends JFrame {

    XOButton[] xob = new XOButton[9];
    private JLabel turn;

    public static int state;

    public TicTacToe() {
        super("TicTacToe");

        //add XOButtons to panel
        JPanel center = new JPanel();
        state = 0;

        JLabel turn = new JLabel("X's turn");

        center.setLayout(new GridLayout(3, 3, 2, 2));
        //action listener
        ButtonListener bl = new ButtonListener();
        for (int i = 0; i < 9; i++) {
            xob[i] = new XOButton();
            xob[i].addActionListener(bl);
            center.add(xob[i]);
        }

        //add panel to frame
        setLayout(new BorderLayout());
        add(center, BorderLayout.CENTER);
        add(turn, BorderLayout.NORTH);

    }

    //inner action listener class
    private class ButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent ae) {
            for (int i = 0; i < 9; i++) {
                if(ae.getSource() == xob[i] && xob[i].getState() == XOButton.NONE && state == 0) {
                    xob[i].setState(XOButton.X);
                    state = 1;
                    //turn.setText("O's turn");

                } else if(ae.getSource() == xob[i] && xob[i].getState() == XOButton.NONE && state == 1) {
                    xob[i].setState(XOButton.O);
                    state = 0;
                }
            }
        }
    }
}
xhv8bpkk

xhv8bpkk1#

猜测:您的错误是nullpointerexception,因为 turn 为空。解决方案:不要对变量进行阴影处理。换句话说,您在构造函数中声明turn变量,而字段为null。
例如。,

public class TicTacToe extends JFrame{
XOButton[] xob = new XOButton[9];
private JLabel turn;

public static int state;

public TicTacToe() {
    super("TicTacToe");

    //add XOButtons to panel
    JPanel center = new JPanel();
    state = 0;

    JLabel turn = new JLabel("X's turn");  //****you're re-declaring turn here!

更好:

public class TicTacToe extends JFrame{
XOButton[] xob = new XOButton[9];
private JLabel turn;

public static int state;

public TicTacToe() {
    super("TicTacToe");

    //add XOButtons to panel
    JPanel center = new JPanel();
    state = 0;

    turn = new JLabel("X's turn");  //****Note the difference?

今后,如果您有类似的问题,请张贴整个错误消息,并指出哪一行抛出异常,因为它将极大地帮助我们!

相关问题