XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.

advertisement

Google Web Toolkit
by Bruce Perry | Pages: 1, 2, 3, 4, 5

Entry Point

The MyForm.java class implements the GWT API interface EntryPoint. As a result, the class must implement the onModuleLoad() method, which the browser's JavaScript engine calls when the browser loads your Ajax application.

In other words, the GWT compiler compiles this class into JavaScript code. The MyForm.java class sets up the form widgets for the browser view. The class also determines the response to the users clicking the OK, Submit button. The comments in the code describe exactly what's going on, so I won't repeat these comments in the article's text.

package com.parkerriver.gwt.testapp.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import java.util.Iterator;

public class MyForm implements EntryPoint {
    //The id pf the HTMl div element that provides
    //status info
    private String statusId = "status";
    //A Grid object; actually, an HTML table
    private Grid grid = new Grid(5, 2);
    //Other user interface objects
    private Label  nmLab = new Label();
    private Label  ageLab = new Label();
    private Label  homeLab = new Label();
    private TextBox nmTxt = new TextBox();
    private TextBox ageTxt = new TextBox();
    private TextBox homeTxt = new TextBox();
    private Button okBut = new Button();
    private TextArea tarea = new TextArea();
    /* This method is called when the browser loads
        the application. The method sets up 3 Labels and TextBoxes; as
        well as a Button and the TextArea that will display the server's
        response.  */
     public void onModuleLoad() {

        //set up labels  and text fields
        nmLab.setText("Full Name:");
        nmTxt.setMaxLength(25);
        ageLab.setText("Age:");
        ageTxt.setVisibleLength(3);
        ageTxt.setMaxLength(3);
        homeLab.setText("Home country:");
        homeTxt.setMaxLength(25);
        //Place these widgets within the Grid
        grid.setWidget(0,0,nmLab);
        grid.setWidget(0,1,nmTxt);
        grid.setWidget(1,0,ageLab);
        grid.setWidget(1,1,ageTxt);
        grid.setWidget(2,0,homeLab);
        grid.setWidget(2,1,homeTxt);

        //set up button and textarea
        tarea.setCharacterWidth(40);
        tarea.setVisibleLines(25);
        okBut.setText("OK, Submit");
        //Give the button its behavior by adding a listener object;
        //literally, a ClickListener object that has an
        //onClick event handler.
        okBut.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                //Notify the user of the remote 
                //procedure call status; see method below
                showRpcStatus(true);
                //Create an instance of the client-side stub for our 
                //server-side service.
                ShowRespServiceAsync respService =
                        (ShowRespServiceAsync) GWT
                                .create(ShowRespService.class);
                ServiceDefTarget endpoint = (ServiceDefTarget) respService;
                //The implementation of our service is an instance
                //of RemoteServiceServlet, so provide the server path
                //to the servlet; this path appears in web.xml
                endpoint.setServiceEntryPoint("/parkerriver/s/showresp");
                //This interface handles the response from the server.
                //It will display the server's response in a TextArea.
                //The display will be in a red color if the message
                //represents an error.
                AsyncCallback callback = new AsyncCallback() {
                    public void onSuccess(Object result) {
                        //If there is one, remove the 'warning' CSS style 
                        //relating to any error text's appearance
                        if(tarea.getStyleName().
                                equalsIgnoreCase("warning")){
                            tarea.removeStyleName("warning");
                        }
                        //Textarea displays the server's return value
                        tarea.setText((String)result);
                    }
                    public void onFailure(Throwable caught) {
                        //Textarea displays any exception messages
                        tarea.setStyleName("warning");
                        tarea.setText(
                            "Server request raised an error; Java exception : "+
                            caught == null ? "An unknown exception" :
                                        caught.getMessage());
                    }
                };
                //Call the service method, validating the form
                //values first.
                try{
                    respService.displayResponse(
                            getPanelTextContent(grid,true),
                            callback);
                } catch (Exception e) {
                    tarea.setStyleName("warning");
                    tarea.setText("Server request raised an error: "+
                            e.getMessage());
                }  finally {
                    //Remove the status message when we are finished
                    //making the RPC call
                    showRpcStatus(false);
                }
            }
        });

        //Now add these widgets to the grid
        grid.setWidget(3,0,okBut);
        grid.setWidget(3,1,tarea);
        //set the vertical alignment for the OK button's cell
        grid.getCellFormatter().setVerticalAlignment(3,0,
                HasVerticalAlignment.ALIGN_TOP);
        //set the vertical alignment for the TextBoxes,
        //in order to line them up properly
        grid.getCellFormatter().setVerticalAlignment(0,1,
                HasVerticalAlignment.ALIGN_BOTTOM);
        grid.getCellFormatter().setVerticalAlignment(1,1,
                HasVerticalAlignment.ALIGN_BOTTOM);
        grid.getCellFormatter().setVerticalAlignment(2,1,
                HasVerticalAlignment.ALIGN_BOTTOM);


        //Add the grid, actually an HTML table, to a div element
        //in the browser's HTML with id value "gridholder"
        RootPanel.get("gridholder").add(grid);
    }
    /*Initiate a simple check for blank fields, then return the 
      submitted values as a single string.
      HasWidgets is an interface that Grid and other panel type
      objects implement. Therefore, we can pass the grid into
      this method; iterate over its contained TextBoxes, and
      validate the TextBox's content.
    */
    private String getPanelTextContent(HasWidgets panelType,
                                       boolean validateContent) {
        StringBuffer buf = new StringBuffer("");
        String tmp = null;
        if(panelType != null) {
           //for the sake of brevity, clipped...
        }
        //return the TextBoxes content each 
        //separated by a space
        return buf.toString();
    }
    
    /* Overly simplified validation! */
    private boolean validateText(String _content){
        return _content.length() > 0;

    }

    private int getTextboxCount(HasWidgets pType){
        //Not shown: returns the number of TextBox widgets
        //in the panel
    }

    /* Show the user a status message if the
     response takes long to arrive.*/
    private void showRpcStatus(boolean _on){
        //Use the GWT DOM API for JavaScript DOM
        //programming
        Element el = DOM.getElementById(statusId);
        if(el != null)  {
            if(_on) {
                DOM.setStyleAttribute(el,"font-size","1.2em");
                DOM.setStyleAttribute(el,"color","green");
                DOM.setInnerHTML(el, "Fetching server info...");
            }  else{
                DOM.setInnerHTML(el, "");
            }
        }

    }
}

Most of this code deals with the GWT API. It is interesting to note that if you have to implement JavaScript DOM programming, as in the showRpcStatus() method, you can accomplish this task in Java by using the com.google.gwt.user.client.DOM class.

Pages: 1, 2, 3, 4, 5

Next Pagearrow