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.
- Add an
ActionListener
to each terrain element as that terrain object is created ininitGUI()
. (Hint: use TerrainButton’saddActionListener()
method, with a newActionListener
object as the parameter value. In theActionListener
, add a public method calledactionPerformed()
.actionPerformed()
should have one parameter, anActionEvent
callede
, and return nothing.) - In
actionPerformed()
, create aTerrainButton
object calledbutton
, initialized by getting the source ofe
. Use ActionEvent’sgetSource()
method. - Create integers called
row
andcol
that are initialized with the row and column values frombutton
, respectively. Use TerrainButton’sgetRow()
andgetCol()
methods. - Call
clickedTerrain()
withrow
andcol
.
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.