Nicolas Frankel is an IT consultant with 10 years experience in Java / JEE environments. He likes his job so much he writes technical articles on his blog and reviews technical books in his spare time. He also tries to find other geeks like him in universities, as a part-time lecturer. Nicolas is a DZone MVB and is not an employee of DZone and has posted 217 posts at DZone. You can read more from them at their website. View Full User Profile

Use views, not windows in Vaadin

02.29.2012
| 9311 views |
  • submit to reddit
In Vaadin 6, the Window class is used for both main windows - i.e. windows that fill the entire screen, and popup windows aka subwindows.

This has lead some developers (including me) to think main windows could be set and then removed later on: this is not the case and may lead to nasty bugs when the page is refreshed by the user just after having switched main windows.
Note: Vaadin 7 tackles the problem by merging the application and the main window into a single class (more in a later article).

In essence, when one has to fundamentally change what is shown to the user, one should use a custom component I call view. A view is just a group of components that are laid out together. Then, when we need to switch windows, we keep the main window and switch its content from one view to another: the main window becomes a just a placeholder. As an added value, since the main window is kept, it has always access to the parent application.

The application becomes something like this:

public class MyApplication extends Application {
 
  @Override
  public void init() {
 
    setMainWindow(new Window());
  }
}

The view should look something like that:

public class LoginView extends CustomComponent {
 
  private TextField login = new TextField("Login");
 
  private TextField password = new TextField("Password");
 
  public LoginView() {
 
    FormLayout layout = new FormLayout();
 
    setCompositionRoot(layout);
 
    layout.addComponent(login);
    layout.addComponent(password);
 
    Button button = new Button("Login");
 
    layout.addComponent(button);
 
    button.addListener(new ClickListener() {
 
      @Override
      public void buttonClick(ClickEvent event) {
 
        getApplication().getMainWindow().setContent(new MainView());
      }
    });
  }
}

Important notes:

  1. MainView is another custom component with the components we want displayed
  2. don't forget the separation of concerns, the switching behavior mixed in the GUI code is shown only for readability purposes
  3. login in and out should perhaps be designed at the application level so we could call getApplication().login()
Published at DZone with permission of Nicolas Frankel, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: