---
title: Handling Events with Listeners
order: 4
layout: page
---

[[application.events]]
= Handling Events with Listeners

Let us put into practice what we learned of event handling in
<<../architecture/architecture-events#architecture.events,"Events
and Listeners">>. You can implement listener interfaces by directly using lambda expressions, method references or anonymous classes.

For example, in the following, we use a lambda expression to handle button click
events in the constructor:


[source, java]
----
layout.addComponent(new Button("Click Me!",
    event -> event.getButton().setCaption("You made click!")));
----

Directing events to handler methods is easy with method references:

[source, java]
----
public class Buttons extends CustomComponent {
    public Buttons() {
        setCompositionRoot(new HorizontalLayout(
            new Button("OK", this::ok),
            new Button("Cancel", this::cancel)));
    }

    private void ok(ClickEvent event) {
        event.getButton().setCaption ("OK!");
    }

    private void cancel(ClickEvent event) {
        event.getButton().setCaption ("Not OK!");
    }
}
----


[[application.events.anonymous]]
== Using Anonymous Classes

The following example defines an anonymous class that inherits the [classname]#Button.ClickListener# interface.


[source, java]
----
// Have a component that fires click events
Button button = new Button("Click Me!");

// Handle the events with an anonymous class
button.addClickListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        button.setCaption("You made me click!");
    }
});
----

Most components allow passing a listener to the constructor.
Note that to be able to access the component from the anonymous listener class,
you must have a reference to the component that is declared before the
constructor is executed, for example as a member variable in the outer class.
You can also to get a reference to the component from the event object:


[source, java]
----
final Button button = new Button("Click It!",
  new Button.ClickListener() {
    @Override
    public void buttonClick(ClickEvent event) {
        event.getButton().setCaption("Done!");
    }
  });
----
