如果已经点击了,请停止Jbutton进行更改
问题描述:
新手程序员试图制作一个tic tac脚趾GUI游戏。虽然我坚持我的程序。我不知道如何检查两次击中同一方格。我在想一个if语句我的ActionListener提到如果已经点击了,请停止Jbutton进行更改
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
}
的工作,但我不能让程序正常工作中。我尝试了newTurn.getmodel()。isPressed(),但这并不起作用,现在用我当前的代码,程序在每次移动后都会输出错误消息,并且更改仍然出现在板上。这是我的这种方法的代码。任何帮助表示赞赏。
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++;
}
开关移动只是一个int设置为0所以evens是X和O是奇数。我的if(newTurn.isEnabled())是我的问题
答
这是我解决的代码。
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++;
}
在actionPerformed()方法中,在单击按钮后将按钮设置为setEnabled(false)。然后,当游戏结束时,先前禁用的按钮将通过resetButtons方法设置为setEnabled(true)。
使用'JToggleButton'或禁用进一步交互中的按钮 – MadProgrammer