gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:33:42 25 4
gpt4 key购买 nike

我正在用 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);
}

}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com