- Data-Centric Applications with Vaadin 8
- Alejandro Duarte
- 160字
- 2021-08-27 18:40:16
Events and listeners
In a Vaadin application, the behavior is added through listeners. A 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");
}