有效跟踪第一次和第二次点击Java - 2d数组gui

时间:2015-03-15 21:47:19

标签: java click jbutton actionlistener

我正在寻找一种更有效的跟踪第一次和第二次点击的方法。开发棋盘游戏以及我现在工作的方式我不觉得我可以添加所有要求

以下是我目前跟踪点击次数的方法。

  public void actionPerformed(ActionEvent ae){
     for(int row = 0; row < boardGame.length; row++){   
     for(int col = 0; col < boardGame.length; col++){
        if(ae.getSource() == boardGame[row][col]){
           if(isFirstClick){                                   
              fromRow = boardGame[row][col].getRow();
              fromCol = boardGame[row][col].getCol();
              this.checkTurn();
              System.out.println(boardGame[row][col].getPlayer());
              isFirstClick = false;
              }// end if
           else {
              toRow = boardGame[row][col].getRow();
              toCol = boardGame[row][col].getCol();
              movePiece();
              isFirstClick = true;
              createBoard();
           }// end else
        }// end get source
    }//end col
  } //end row   
}

因此,虽然这适用于我目前的功能..我似乎无法使用移动验证。有没有更好的方法来获得第一次和第二次点击?

1 个答案:

答案 0 :(得分:0)

你的游戏看起来像国际象棋。我建议你看一下 Command 模式。每次用户点击您的电路板或电路板上的某个单元格或者您生成的任何新事件时,该事件都会转换为将其存储在列表或队列中的命令。然后,您将始终知道有多少次点击和其他操作以及何时进行。此外,您还可以实现取消移动等功能。

这是一个揭示我的想法的例子:

static abstract class Event {

}

static class CellClicked extends Event {
    int userId;
    int row;
    int col;
}

static abstract class Command {
    void execute();
}

static class MovePieceCommand extends Command {
    //... implementation    
}

static class SelectPieceCommand extends Command {
    //... implementation
}

static class EventHandler {

    void handle(Event event) {
        //..
    }
}

您的事件会被事件监听器转换为命令。执行命令并在其中实现游戏的业务逻辑。