Ariel
Ariel

Reputation: 2742

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!");

    }


}

Upvotes: 1

Views: 277

Answers (7)

rancidfishbreath
rancidfishbreath

Reputation: 3994

Let's walk through the code:

In javax.swing.AbstractButton there is a method called addActionListener where the code is:

public void addActionListener(ActionListener l) {
  listenerList.add(ActionListener.class, l);
}

listenerList is defined in javax.swing.JComponent as:

protected EventListenerList listenerList = new EventListenerList();

When an event occurs fireActionPerformed in javax.swing.AbstractButton is called. The code looks like:

protected void fireActionPerformed(ActionEvent event) {
  // Guaranteed to return a non-null array
  Object[] listeners = listenerList.getListenerList();
  ActionEvent e = null;
  // Process the listeners last to first, notifying
  // those that are interested in this event
  for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==ActionListener.class) {
      // Lazily create the event:
      if (e == null) {
        String actionCommand = event.getActionCommand();
        if(actionCommand == null) {
          actionCommand = getActionCommand();
        }
        e = new ActionEvent(AbstractButton.this,
            ActionEvent.ACTION_PERFORMED,
            actionCommand,
            event.getWhen(),
            event.getModifiers());
      }
      ((ActionListener)listeners[i+1]).actionPerformed(e);
    }
  }
}

The most important part is the last line that says:

((ActionListener)listeners[i+1]).actionPerformed(e);

This is the line of code that calls your actionPerformed() method

Upvotes: 1

M Sach
M Sach

Reputation: 34424

Basically you are going thru observer pattern where observers registers themselves with subject.Now whenever this is some event triggers on subject , subject notifies the different observers. Here Button is subject and SimpleGui1B(basically listener) is observer.Now lets come to your code snippet

 button.addActionListener(this);

In above line , button is subject and this is listener/observer. JButton has designed in a way, whenever some event(click in this case) happens on button, observers will be notified thru the method actionPerformed

Upvotes: 0

christopher
christopher

Reputation: 27346

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.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691755

In the JButton class, the keyboard and mouse events are handled, and once the button detects a click, it iterates to its action listeners and calls them:

ActionEvent event = new ActionEvent(...);
for (ActionListener listener : addedListeners) {
    listener.actionPerformed(event);
}

Listeners are just callback objects.

Upvotes: 2

joaonlima
joaonlima

Reputation: 618

What the code

button.addActionListener(this);

does is add your class (using the keyword this) to be the action listener of the button you created. What this means, is that the button will call your class whenever an action (such as click) happens. This is why you need the method

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

Because it will be called by the button

Upvotes: 0

Imre Kerr
Imre Kerr

Reputation: 2428

button.addActionListener(this); tells button that this wants to know whenever the button is clicked. From then on, whenever the button is clicked it will go through its list of registered ActionListeners and call the actionPerformed method on each one.

Upvotes: 0

Michal Borek
Michal Borek

Reputation: 4624

That means that the class which is invoking this code is a listener of button changes. So that button will invoke "actionPerformed" on this particular class.

Upvotes: 0

Related Questions