Handling Events with Listeners

Let us put into practice what we learned of event handling in “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:

Java

  1. layout.addComponent(new Button("Click Me!",
  2. event -> event.getButton().setCaption("You made click!")));

Directing events to handler methods is easy with method references:

Java

  1. public class Buttons extends CustomComponent {
  2. public Buttons() {
  3. setCompositionRoot(new HorizontalLayout(
  4. new Button("OK", this::ok),
  5. new Button("Cancel", this::cancel)));
  6. }
  7. private void ok(ClickEvent event) {
  8. event.getButton().setCaption ("OK!");
  9. }
  10. private void cancel(ClickEvent event) {
  11. event.getButton().setCaption ("Not OK!");
  12. }
  13. }

Using Anonymous Classes

The following example defines an anonymous class that inherits the Button.ClickListener interface.

Java

  1. // Have a component that fires click events
  2. Button button = new Button("Click Me!");
  3. // Handle the events with an anonymous class
  4. button.addClickListener(new Button.ClickListener() {
  5. public void buttonClick(ClickEvent event) {
  6. button.setCaption("You made me click!");
  7. }
  8. });

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:

Java

  1. final Button button = new Button("Click It!",
  2. new Button.ClickListener() {
  3. @Override
  4. public void buttonClick(ClickEvent event) {
  5. event.getButton().setCaption("Done!");
  6. }
  7. });