Data-Centric Applications with Vaadin 8
上QQ阅读APP看书,第一时间看更新

Events and listeners

In a Vaadin application, the behavior is added through listenersA listener fires an event when the corresponding action happens, usually caused by the interaction of the user with the UI. Two of the most common listeners in Vaadin are ClickListener (for buttons) and ValueChangeListener (for input components). Listeners are usually defined by implementing a functional interface, which allows you to react to an event using a method reference:

protected void init(VaadinRequest vaadinRequest) { 
Button button = new Button("Click this");
button.addClickListener(this::buttonClicked);
}
...
private void buttonClicked(Button.ClickEvent event) {
Notification.show("Thanks for clicking");
}

You can also use a Lambda expression instead:

button.addClickListener(
event -> Notification.show("Thanks for clicking"));

And to make it more readable and testable, extract the listener logic to a new method, passing only what's needed as parameters (in this case, nothing is needed):

protected void init(VaadinRequest vaadinRequest) { 
...
button.addClickListener(event -> buttonClicked());
}
...
private void buttonClicked() {
Notification.show("Thanks for clicking");
}