Checking the Terrain Button on Click

Learn how to check the terrain button, its neighbors, and its neighbor's neighbor when the terrain button is clicked.

Checking a terrain when clicked

Next, listen for any of the terrain buttons to be clicked.

  1. Add an ActionListener to each terrain element as that terrain object is created in initGUI(). (Hint: use TerrainButton’s addActionListener() method, with a new ActionListener object as the parameter value. In the ActionListener, add a public method called actionPerformed(). actionPerformed() should have one parameter, an ActionEvent called e, and return nothing.)
  2. In actionPerformed(), create a TerrainButton object called button, initialized by getting the source of e. Use ActionEvent’s getSource() method.
  3. Create integers called row and col that are initialized with the row and column values from button, respectively. Use TerrainButton’s getRow() and getCol() methods.
  4. Call clickedTerrain() with row and col.

Note: Do not click the run button just yet. The code will have a syntax error because clickedTerrain() does not exist yet.

...
private void initGUI() {
    ...
    for (int row = 0; row < GRIDSIZE; row++) {
        for (int col = 0; col < GRIDSIZE; col++) {
            terrain[row][col] = new TerrainButton(row, col);
            terrain[row][col].add_____________(new ______________ {
                ______________ actionPerformed(____________) {
                    ________________ button = (__________) e.___________;
                    ________ row = ______________;
                    ________ col = _______________;
                    clickedTerrain(__________________);
                }
            });
            centerPanel.add(terrain[row][col]);
    ...

Get hands-on with 1200+ tech skills courses.