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.

  1. Add an action listener to each lightButton as the light button is created in initGUI(). Use LightButton’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, and return nothing.
  2. In the actionPerformed() method:
  • Create a LightButton object called button, initialized by getting the source from e. Use ActionEvent’s getSource() method.
  • Create an integer called row, initialized by getting the row from the button. Use LightButton’s getRow() method.
  • Create an integer called col, initialized by getting the column from the button. Use LightButton’s getCol() method.
  • Call toggleLights(), passing in the values of row and col.

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 = _______________;

Get hands-on with 1200+ tech skills courses.