Finding the current UI and page and vaadin session

There are many cases where you need a reference to the active UI, Page or VaadinServiceSession, for instance for showing notifications in a click listener. It is possible to get a reference to the component from the event and then a reference from the component to the UI but Vaadin also offers an easier way through two static methods:

Java

  1. UI.getCurrent()
  2. Page.getCurrent()
  3. VaadinSession.getCurrent()

For example when you want to show the name of the current UI class:

Java

  1. Button helloButton = new Button("Say Hello");
  2. helloButton.addClickListener(new ClickListener() {
  3. @Override
  4. public void buttonClick(ClickEvent event) {
  5. Notification.show("This UI is "
  6. + UI.getCurrent().getClass().getSimpleName());
  7. }
  8. });

Similarly for VaadinServiceSession, for instance to find out if the application is running in production mode:

Java

  1. public void buttonClick(ClickEvent event) {
  2. String msg = "Running in ";
  3. msg += VaadinSession.getCurrent().getConfiguration()
  4. .isProductionMode() ? "production" : "debug";
  5. Notification.show(msg);
  6. }

And finally similarly for Page. For instance adding a browser window resize listener can be added like this:

Java

  1. Page.getCurrent().addBrowserWindowResizeListener(
  2. new Page.BrowserWindowResizeListener() {
  3. @Override
  4. public void browserWindowResized(BrowserWindowResizeEvent event) {
  5. Notification.show("Browser resized to " + event.getWidth() + "x" + event.getHeight());
  6. }
  7. });

Note that these are based on ThreadLocal so they won’t work in a background thread (or otherwise outside the standard request scope).