Toggle the LightButton's Light on Clicking
Learn to toggle the light of a clicked button and its neighbouring buttons.
We'll cover the following
- Event source
- Make clicking a LightButton toggle its light
- Make clicking a corner LightButton toggle the correct neighbors’ lights
- Make clicking a middle side LightButton toggle the correct neighbors’ lights
- Make clicking a center LightButton toggle the correct neighbors’ lights
- Starting framed with a completed frame
- Starting framed with a random valid puzzle
- Key points
Event source
In the programs we have created so far, we have not done anything with the ActionEvent
variable passed to the actionPerformed()
method of the ActionListener
. However, many useful methods can process an ActionEvent
. One such method will get the source of the event.
Make clicking a LightButton
toggle its light
Now we will add action listeners to the LightButtons
. The program can call any of LightButton’s methods once it gets the source LightButton
object from the ActionEvent
.
- Add an action listener to each
lightButton
as the light button is created ininitGUI()
. Use LightButton’saddActionListener()
method with a newActionListener
object as the parameter value. In theActionListener
, add a public method calledactionPerformed()
.actionPerformed()
should have one parameter, anActionEvent
, and return nothing. - In the
actionPerformed()
method:
- Create a
LightButton
object calledbutton
, initialized by getting the source frome
. Use ActionEvent’sgetSource()
method. - Create an integer called
row
, initialized by getting the row from the button. Use LightButton’sgetRow()
method. - Create an integer called
col
, initialized by getting the column from the button. Use LightButton’sgetCol()
method. - Call
toggleLights()
, passing in the values ofrow
andcol
.
If you try executing after implementing the code, the program will have a syntax error because toggleLights()
does not exist yet.
...
private void initGUI() {
...
lightButton[row][col] = new LightButton(row, col);
lightButton[row][col].addActionListener(_______________ {
_______________ actionPerformed(___________ e) {
_____________ button = (LightButton) e.getSource();
______ row = _______________;
______ col = _______________;
toggleLights(_____________);
}
});
centerPanel.add(lightButton[row][col]);
...
Get hands-on with 1200+ tech skills courses.