遵照软件业的悠久传统, 在学习一个新的开发框架时, 先来写写著名的 "Hello World!". 首先, 我们使用最基本的服务器端 API.
import com.vaadin.server.VaadinRequest; import com.vaadin.ui.Label; import com.vaadin.ui.UI; @Title("My UI") @Theme("valo") public class HelloWorld extends UI {源代码解释:一个 Vaadin 应用程序包含一个或多个 UI, UI 由 com.vaadin.ui.UI 类继承而来. 一个 UI 就是 Vaadin 应用程序运行时所在的 Web 页面的一部分. 在同一页面中, 一个应用程序也可以包含多个 UI, 在 portal 中更是如此, 在浏览器的不同窗口或不同 tab 中当然也是如此. 一个 UI 会关联到一个用户 session, 而 session 会为每一个使用这个应用程序的用户单独创建. 在我们的 Hello World UI 中, 当用户访问页面时会发生对应用程序的初次访问, 此时 session 就被创建出来, init() 方法就在这个时候被调用。@Override protected void init(VaadinRequest request) { // Create the content root layout for the UI VerticalLayout content = new VerticalLayout(); setContent(content); // Display the greeting content.addComponent(new Label("Hello World!")); // Have a clickable button content.addComponent(new Button("Push Me!", new ClickListener() { @Override public void buttonClick(ClickEvent e) { Notification.show("Pushed!"); } })); }
}
以上代码中的按钮及其监听事件部分可以简写为:(使用lambda表达式)
content.addComponent(new Button("Push Me!",event -> Notification.show("Pushed!")));
如果要开发一个纯客户端应用程序, 你可以非常简单地输出 Hello World 文字, 而且开发语言仍然使用 Java, 如下:
public class HelloWorld implements EntryPoint {@Override public void onModuleLoad() { RootPanel.get().add(new Label("Hello, world!")); }
}
这个例子中我们没有设置页面标题, 因为标题通常由上述代码执行时所在的 HTML 页面来定义. 这个应用程序将被 Vaadin 客户端编译器 (或者 GWT 编译器)编译为 JavaScript. 这种方法通常用来开发客户端 widget, 然后供服务器端 Vaadin 应用程序使用。