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.

FindingTheCurrentUIAndPageAndVaadinSession.asciidoc 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. ---
  2. title: Finding The Current UI And Page And Vaadin Session
  3. order: 18
  4. layout: page
  5. ---
  6. [[finding-the-current-ui-and-page-and-vaadin-session]]
  7. = Finding the current UI and page and vaadin session
  8. There are many cases where you need a reference to the active `UI`, `Page`
  9. or `VaadinServiceSession`, for instance for showing notifications in a
  10. click listener. It is possible to get a reference to the component from
  11. the event and then a reference from the component to the UI but Vaadin
  12. also offers an easier way through two static methods:
  13. [source,java]
  14. ....
  15. UI.getCurrent()
  16. Page.getCurrent()
  17. VaadinSession.getCurrent()
  18. ....
  19. For example when you want to show the name of the current UI class:
  20. [source,java]
  21. ....
  22. Button helloButton = new Button("Say Hello");
  23. helloButton.addClickListener(new ClickListener() {
  24. @Override
  25. public void buttonClick(ClickEvent event) {
  26. Notification.show("This UI is "
  27. + UI.getCurrent().getClass().getSimpleName());
  28. }
  29. });
  30. ....
  31. Similarly for `VaadinServiceSession`, for instance to find out if the
  32. application is running in production mode:
  33. [source,java]
  34. ....
  35. public void buttonClick(ClickEvent event) {
  36. String msg = "Running in ";
  37. msg += VaadinSession.getCurrent().getConfiguration()
  38. .isProductionMode() ? "production" : "debug";
  39. Notification.show(msg);
  40. }
  41. ....
  42. And finally similarly for `Page`. For instance adding a browser window
  43. resize listener can be added like this:
  44. [source,java]
  45. ....
  46. Page.getCurrent().addBrowserWindowResizeListener(
  47. new Page.BrowserWindowResizeListener() {
  48. @Override
  49. public void browserWindowResized(BrowserWindowResizeEvent event) {
  50. Notification.show("Browser resized to " + event.getWidth() + "x" + event.getHeight());
  51. }
  52. });
  53. ....
  54. *Note* that these are based on `ThreadLocal` so they won't work in a
  55. background thread (or otherwise outside the standard request scope).