尝试编写Tic Tac Toe用于学习目的

时间:2018-06-13 17:56:56

标签: java swing

我对编码很陌生,所以请善待!

我正在尝试在Java Swing中编写一个tic tac toe游戏。但我有一个非常烦人的错误,我不明白为什么会出现这个错误。谁能帮助我理解为什么请?

这是我的代码:

Hide out of stock items from the catalog

正如您所看到的,如果第一个按钮的文本是“X”,我正在尝试使用方法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.JPanel; public class Board extends JFrame { private JPanel pan = new JPanel(); private boolean player1 = true; private JButton[] tab_but = new JButton[9]; public Board() { initializeComponent(); } public void initializeComponent() { this.setTitle("TicTacToe"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400, 400); this.setLocationRelativeTo(null); this.setResizable(false); this.setContentPane(pan); GridLayout gl = new GridLayout(3,3); pan.setLayout(gl); for (JButton jButton : tab_but) { jButton = new JButton(); pan.add(jButton); jButton.addActionListener(new ButtonListener()); } this.setVisible(true); } class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e) { if (player1) { ((JButton)e.getSource()).setText("X"); checkWin(); player1=false; } else { ((JButton)e.getSource()).setText("O"); player1=true; } } } public void checkWin() { if(tab_but[0].getText().equals("X")) { System.out.println("hi"); } } } 进行检查。但是控制台返回checkWin(),即使X已经写在第一个按钮上(当我点击第一个按钮时)

1 个答案:

答案 0 :(得分:0)

什么行抛出NullPointerException,.equals("X").setText("X")?我相信这是因为您初始化数组tab_but但不填充对象,因此tab_but[0]为空。