Java 如何使按钮不被点击?
我正在做一个井字游戏,我如何使按钮只有一个特定的字母喜欢。当点击一个按钮时,它会转到x,但一旦再次按下,它就会转到o。我如何使其固定,而不是在按下后使其固定Java 如何使按钮不被点击?,java,image,swing,user-interface,Java,Image,Swing,User Interface,我正在做一个井字游戏,我如何使按钮只有一个特定的字母喜欢。当点击一个按钮时,它会转到x,但一旦再次按下,它就会转到o。我如何使其固定,而不是在按下后使其固定 import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TicTacToeSample extends JFrame implements ActionListener
{
private JFrame game = new JFrame("TicTacToe");
private JButton button1 = new JButton("");
private JButton button2 = new JButton("");
private JButton button3 = new JButton("");
private JButton button4 = new JButton("");
private JButton button5 = new JButton("");
private JButton button6 = new JButton("");
private JButton button7 = new JButton("");
private JButton button8 = new JButton("");
private JButton button9 = new JButton("");
private String letter = "X";
private int count = 0;
private boolean win = false;
public TicTacToeSample()
{
game.setSize(300,300);
game.setDefaultCloseOperation(EXIT_ON_CLOSE);
game.setLayout(new GridLayout(3, 3));
game.add(button1);
game.add(button2);
game.add(button3);
game.add(button4);
game.add(button5);
game.add(button6);
game.add(button7);
game.add(button8);
game.add(button9);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
button7.addActionListener(this);
button8.addActionListener(this);
button9.addActionListener(this);
game.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
count++;
if (count == 1 || count == 3 || count == 5 || count == 7 || count == 1)
{
letter = "X";
}
else if (count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "O";
}
if(event.getSource()== button1)
{
button1.setText(letter);
}
if(event.getSource()== button2)
{
button2.setText(letter);
}
}
public static void main(String[] paramArrayOfString)
{
TicTacToeSample board = new TicTacToeSample();
}
}
在ActionListener中,通过调用ActionEvent参数上的
getSource()
来获取按下的按钮。通过调用getText()
检查其文本(如果有)。如果它有文本,不要更改它。简单 在ActionListener中,通过调用ActionEvent参数上的getSource()
来获取按下的按钮。通过调用getText()
检查其文本(如果有)。如果它有文本,不要更改它。简单 删除操作列表禁用按钮删除操作列表禁用按钮