Listing 1:Sample GWT Application
1 package com.sample.myProject.client;
2 import com.google.gwt.core.client.EntryPoint; 3 import com.google.gwt.user.client.ui.Button; 4 import com.google.gwt.user.client.ui.HorizontalPanel; 5 import com.google.gwt.user.client.ui.Label; 6 import com.google.gwt.user.client.ui.PasswordTextBox; 7 import com.google.gwt.user.client.ui.RootPanel; 8 import com.google.gwt.user.client.ui.TextBox;
/** * This class is used to demostrate how to add widget onto the Web page */ 9 public class DemoClient implements EntryPoint { /** * This is the entry point method, when the module is load, this method * will be automatically invoked. */ 10 public void onModuleLoad() { 11 Label labelName = new Label(); 12 Label labelPassword = new Label(); 13 TextBox tbName = new TextBox(); 14PasswordTextBox tbPassword = new PasswordTextBox(); 15Button button = new Button(); 16 17 labelName.setText("Name: "); 18 labelPassword.setText("Password: "); 19 button.setText("submit"); 20 21 HorizontalPanel hPanel = new HorizontalPanel(); 22 HorizontalPanel hPanel2 = new HorizontalPanel(); 23 24 hPanel.add(labelName); 25 hPanel.add(tbName); 26 hPanel2.add(labelPassword); 27 hPanel2.add(tbPassword); 28 RootPanel.get().add(hPanel); 29 RootPanel.get().add(hPanel2); 30 RootPanel.get().add(button); 31 } 32 } |
接下来我们分析一下这些程序代码,注意到类DemoClient继承自EntryPoint,所有需要最终被翻译成HTML页面的类都必须继承自EntryPoint,并且需要重写onModuleLoad方法,这个方法会在模块被装载的时候自动调用。因此我们也就需要把我们的添加组件的代码放到这个函数里面。
程序的11至15行分别创建了5个组件的实例。分别是两个Label,一个Button,一个TextBox和一个PasswordTextBox。然后程序的17到19行分别设置了两个Label组件以及一个Button组件的显示内容。程序的21行和22行穿件两个Panel对象,这两个Panel对象的类型都是水平Panel对象。也就是说放在这种Panel里面的组件是被水平排列的。程序的24行到27行分别向这两个Panel对象中加入TextBox组件和Label组件。在程序的最后,将刚才创建好的两个Panel对象以及一个Button对象加到最外层的Panel当中。