Add MouseListener and ActionListener
Add functionality for actually playing the game including accepting a valid word, undo a played tile, and clear all played tiles.
We'll cover the following
If a top row tile is clicked, play it
Only the top row of tiles will need to be clickable. Because a played tile might have to be put back on the board, each tile must have a record of which column it was originally in.
- In
initGUI()
, set the column of theletterPanel
after eachletterPanel
is created using LetterPanel’ssetColumn()
method. - After the double for loop that created all the letter panels for the board, create a loop to repeat
COLS
times with an integer calledcol
as the iteration variable. - Add a mouse listener to each letter panel in the top row of the board. Use
0
andcol
as the indexes for each letter panel. Also, use JPanel’saddMouseListener()
method, with a newMouseAdapter
object as the parameter value. In theMouseAdapter
, add a public method calledmouseReleased()
. ThemouseReleased()
method should takeMouseEvent
parameter callede
, and return nothing. - In
mouseReleased()
:- Create a
LetterPanel
object calledletterPanel
, initialized by getting the source ofe
using MouseEvent’sgetSource()
method. - Call a new method called
click()
, passingletterPanel
as the parameter value.
- Create a
Note: The code will have a syntax error because click()
does not exist yet.
...
private void initGUI() {
...
for(int row=0; row<ROWS; row++) {
for(int col=0; col<COLS; col++) {
LetterPanel letterPanel = letters.pickATile();
letterPanel.________________;
board[row][col] = letterPanel;
boardPanel.add(letterPanel);
}
}
for(_________________) {
board[___][___].addMouseListener(________________ {
_____________ mouseReleased(__________) {
______________ letterPanel = _______________;
_________(letterPanel);
}
});
}
...
Get hands-on with 1200+ tech skills courses.