Skip to content

Instantly share code, notes, and snippets.

@TatuLund
Created February 22, 2023 08:24
Show Gist options
  • Select an option

  • Save TatuLund/9957e86c4d013c4a1ddbc0c648aaec09 to your computer and use it in GitHub Desktop.

Select an option

Save TatuLund/9957e86c4d013c4a1ddbc0c648aaec09 to your computer and use it in GitHub Desktop.
Using key shortcuts is prone to race conditions in edge cases in Vaadin. Here is an example how to close DatePicker and postpone clicking of the button to the next round trip so that we get correct value.
package org.vaadin.tatu;
import java.time.LocalDate;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.KeyModifier;
import com.vaadin.flow.component.Shortcuts;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.router.Route;
@Route("form")
public class DatePickerView extends Div {
public class Person {
private LocalDate birthDate;
private String name;
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public DatePickerView() {
DatePicker datePicker = new DatePicker("Birth date");
TextField textField = new TextField("Name");
Person person = new Person();
Binder<Person> binder = new Binder<>();
binder.forField(datePicker).asRequired().bind(Person::getBirthDate,
Person::setBirthDate);
binder.forField(textField).asRequired().bind(Person::getName,
Person::setName);
binder.readBean(person);
Button save = new Button("Save");
save.addClickListener(e -> {
try {
binder.writeBean(person);
Notification.show("'" + person.getName() + " "
+ person.getBirthDate().toString() + "' saved!");
} catch (ValidationException e1) {
Notification.show("Not valid");
}
});
Shortcuts.addShortcutListener(save, e -> {
datePicker.setOpened(false);
datePicker.getElement().executeJs("return 0;").then(result -> {
save.focus();
save.click();
});
}, Key.KEY_S, KeyModifier.CONTROL).listenOn(this);
add(textField, datePicker, save);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment