Introduction to Google Web Toolkit (GWT)

From Opentaps Wiki
Jump to navigationJump to search

General Concepts

The general idea of GWT is that you write a small "applet" which have a variety of user interface elements, like input boxes, buttons, etc., that communicate asynchronously with your server. They are written in Java, which GWT compiles to cross-platform JavaScript for you. It is then "wired" to your webpage using the id attribute of your HTML. For example, if your HTML has the following tag:

       <tr><td id="newContact"/>
           <td>Rest of opentaps goes here</td>
       </tr>

Then, in GWT, you can add widgets to that part of your webpage with:

  RootPanel.get("newContact").add(vPanel);

The RootPanel of GWT is like the background of your screen. You add panels, buttons, and other widgets to it to make your screen.

Often, the GWT API is a bit low level, and you can save a lot of code by making simple extensions or helpful methods like these for your repetitive UI elements:

private TextBox getTextBox(int visibleLength, int maxLength) {
    TextBox textBox =new TextBox();
    textBox.setVisibleLength(visibleLength);
    textBox.setMaxLength(maxLength);
    return textBox;
} 

private Label getLabel(String text, String styleName) {
    Label label = new Label(text);
    label.setStyleName(styleName);
    return label;
}

private void addWidgetWithLabelToPanel(VerticalPanel panel, String labelText, String labelStyle, Widget widget) {
    panel.add(getLabel(labelText, labelStyle));
    panel.add(widget);
}

To work with the different elements of your GWT "applet", you would define them as variables, instantiate them, pass them along, and then modify them later. For example, you can define an input field called "firstNameInput" in your class:

  private TextBox firstNameInput = null;

Then, you can instantiate it and add it to a panel:

    firstNameInput = new TextBox();
    addWidgetWithLabelToPanel(vPanel, "First Name", "requiredField", firstNameInput); 

Later, when somebody clicks on a button, you can access it by referencing the original object:

createButton.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
// ...
        dialogBox.setText("Create contact " + firstNameInput.getText()); // ...
      }
    });

References