[英]Stop Jbutton from making a change if already clicked
Novice programmer here trying to make a tic tac toe GUI game. 新手程序员在这里尝试制作井字游戏GUI游戏。 I'm stuck with my program though.
我仍然坚持我的程序。 I'm not sure how to place a check on hitting the same square twice.
我不确定如何检查两次击中相同的方块。 I was thinking an if statement inside my actionListener that said
我在想我的actionListener内的if语句说
if(button clicked = True)
{
JOptionPane.showMessageDialog((null, "ERROR", "Button already used.
Please hit again to change back", JOptionPane.ERROR_MESSAGE);
// STOP something along those lines
}
else
{
//Do nothing
}
would work but I can't get the program to work properly. 可以工作,但是我无法使程序正常工作。 I tried newTurn.getmodel().isPressed() and that didn't work and now with my current code the program outputs the error message after each move and the changes still appear on the board.
我尝试了newTurn.getmodel()。isPressed(),但该方法不起作用,现在使用我的当前代码,该程序在每次移动后都会输出错误消息,并且更改仍会出现在板上。 Here's my code for this method.
这是此方法的代码。 Any help is appreciated.
任何帮助表示赞赏。
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton newTurn = (JButton)e.getSource(); //get the particular button that was clicked
if(switchMove%2 == 0)
newTurn.setText("X");
else
newTurn.setText("O");
if(newTurn.isEnabled())
JOptionPane.showMessageDialog(null, "ERROR", "Button already used. Please hit again to change back", JOptionPane.ERROR_MESSAGE);
if(checkForWin() == true)
{
JOptionPane.showConfirmDialog(null, "Game Over.");
resetButtons();
}
switchMove++;
}
switch move is just an int set to 0 so evens are X and O's are odd. 开关的移动只是将int设置为0,因此X是偶数,O是奇数。 My if (newTurn.isEnabled()) is my issue
我的if(newTurn.isEnabled())是我的问题
Here is my resolved code. 这是我解析的代码。
public void resetButtons()
{
for(int i = 0; i <= 8; i++)
{
buttons[i].setText("");
buttons[i].setEnabled(true);
}
}
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton newTurn = (JButton)e.getSource();
if(switchMove%2 == 0)
newTurn.setText("X");
else
newTurn.setText("O");
if(newTurn.isEnabled())
newTurn.setEnabled(false);
if(checkForWin() == true)
{
JOptionPane.showConfirmDialog(null, "Game Over.");
resetButtons();
}
switchMove++;
}
In the actionPerformed() method I set the buttons to setEnabled(false) after a button was clicked. 在actionPerformed()方法中,单击按钮后,将按钮设置为setEnabled(false)。 Then when a game is over the buttons that were previously disabled will be set to setEnabled(true) via the resetButtons method.
然后,当游戏结束时,以前已禁用的按钮将通过resetButtons方法设置为setEnabled(true)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.