What addActionListener does?

后端 未结 5 964
终归单人心
终归单人心 2020-12-31 14:26

I have the following code:

JButton button = new JButton(\"Clear\");
button.addActionListener(this);

As far as I understand I create a butto

5条回答
  •  死守一世寂寞
    2020-12-31 15:04

    An ActionListener is a callback mechanism. Whenever a control it is added to fires an ActionEvent, the public void actionPerformed(ActionEvent e) method will be invoked.

    What I do not understand is where the actionPerformed is called. I see that it is defined within the class but there is no place where this method is called.

    This is called by the internal mechanisms of the UI component. Conceptually, you can think of the code looking a bit like this:

    public class Button {
      private final List listeners = new ArrayList();
    
      public void addActionListener(ActionListener l) {
        listeners.add(l);
      }
    
      public void click() {
        ActionEvent event = new ActionEvent(this, 0, "click");
        for (ActionListener l : listeners) {
          l.actionPerformed(event);
        }
      }
    }
    

提交回复
热议问题