Example #1
0
  /** Creating buttons with coordinates and action listeners */
  private MyButton createButton() {
    // The new buttons counters -
    // will be translates to coordinates
    if (counterX >= size) {
      counterX = 0;
      counterY++;
    }

    MyButton button = new MyButton();

    // set buttons coordinates
    button.x = counterX++;
    button.y = counterY;

    // The buttons properties adjustment
    button.setPreferredSize(new Dimension(50, 50));
    button.setFont(new Font("Dialog", Font.PLAIN, 72));

    // Action listener
    button.addActionListener(
        e -> {
          game.move(new Move(button.x, button.y));
          game.isGameOver();
          button.setText(game.getField()[button.x][button.y] > 0 ? "X" : "O");
          button.setEnabled(false);
          statusStr.setText(game.getState().toString());

          // If the game is over
          // disable all unselected buttons
          if (game.getState().equals(GameState.X_WINS)
              || game.getState().equals(GameState.O_WINS)) {

            for (Component b : gameField.getComponents()) {
              b.setEnabled(false);
            }
          }
        });

    // System.out.println("button " + button.x + " " + button.y);

    return button;
  }