You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

application-events.asciidoc 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. ---
  2. title: Handling Events with Listeners
  3. order: 4
  4. layout: page
  5. ---
  6. [[application.events]]
  7. = Handling Events with Listeners
  8. Let us put into practice what we learned of event handling in
  9. <<../architecture/architecture-events#architecture.events,"Events
  10. and Listeners">>. You can implement listener interfaces by directly using lambda expressions, method references or anonymous classes.
  11. For example, in the following, we use a lambda expression to handle button click
  12. events in the constructor:
  13. [source, java]
  14. ----
  15. layout.addComponent(new Button("Click Me!",
  16. event -> event.getButton().setCaption("You made click!")));
  17. ----
  18. Directing events to handler methods is easy with method references:
  19. [source, java]
  20. ----
  21. public class Buttons extends CustomComponent {
  22. public Buttons() {
  23. setCompositionRoot(new HorizontalLayout(
  24. new Button("OK", this::ok),
  25. new Button("Cancel", this::cancel)));
  26. }
  27. private void ok(ClickEvent event) {
  28. event.getButton().setCaption ("OK!");
  29. }
  30. private void cancel(ClickEvent event) {
  31. event.getButton().setCaption ("Not OK!");
  32. }
  33. }
  34. ----
  35. [[application.events.anonymous]]
  36. == Using Anonymous Classes
  37. The following example defines an anonymous class that inherits the [classname]#Button.ClickListener# interface.
  38. [source, java]
  39. ----
  40. // Have a component that fires click events
  41. Button button = new Button("Click Me!");
  42. // Handle the events with an anonymous class
  43. button.addClickListener(new Button.ClickListener() {
  44. public void buttonClick(ClickEvent event) {
  45. button.setCaption("You made me click!");
  46. }
  47. });
  48. ----
  49. Most components allow passing a listener to the constructor.
  50. Note that to be able to access the component from the anonymous listener class,
  51. you must have a reference to the component that is declared before the
  52. constructor is executed, for example as a member variable in the outer class.
  53. You can also to get a reference to the component from the event object:
  54. [source, java]
  55. ----
  56. final Button button = new Button("Click It!",
  57. new Button.ClickListener() {
  58. @Override
  59. public void buttonClick(ClickEvent event) {
  60. event.getButton().setCaption("Done!");
  61. }
  62. });
  63. ----