2017-10-14 98 views
0

新手程序員試圖製作一個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())是我的問題

+0

使用'JToggleButton'或禁用進一步交互中的按鈕 – MadProgrammer

回答

0

這是我解決的代碼。

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)。