Search code examples
javaswingoopjbuttonactionlistener

Events and Listeners in Java


This should be a basic Java program for beginners to be found on "Head First Java 2nd Edition" on the topic of ActionListener interface.

I didn't understand some of the terminologies used in this program such as

button.addActionListener(this);

when this code executes how is the method actionPerformed is triggered or run or any terminologies you use??

//Program begins from now!!

import javax.swing.*;

import java.awt.event.*;

public class SimpleGui1B implements ActionListener {

    JButton button;

    public static void main(String[] args) {

        SimpleGui1B gui = new SimpleGui1B();
        gui.go();

    }

    public void go(){ //start go
        JFrame frame= new JFrame();
        button=new JButton("Click me");

        frame.getContentPane().add(button);

        button.addActionListener(this);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(300,300);
        frame.setVisible(true);
    }//close go()

    public void actionPerformed(ActionEvent event){
        button.setText("I’ve been clicked!");

    }


}

Solution

  • Let's break down this statement shall we:

    button.addActionListener(this);
    

    Okay, so you're referencing the button object. This is an object of type JButton I presume. The button object has a method called addActionListener. What this does, is add an object that implements the ActionListener interface.

    The class that this occurs in is one of those objects. As you can see at the top it says:

    public class SimpleGui1B implements ActionListener 
    

    So what the program is doing, is saying that the current class (this) will work as a parameter for your method. Then if you look in this class, you have a method actionPerformed.

    public void actionPerformed(ActionEvent event){
        button.setText("I’ve been clicked!");
    
    }
    

    This means that whenever the button is clicked, the code inside the actionPerformed method is called. Another alternative is to say:

    button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
          {
               // Add some code here.
          }
    

    This is doing the exact same thing, only it's defining the class inside the brackets.