miércoles, 17 de agosto de 2011

GWT (Google Web Toolkit) - Primer ejemplo

En la pagina oficial del siito de GWT, encontraremos de forma muy facil y sencilla, paso a paso como tener una aplicación GWT configurada y lista para empezar a trabajar.



Archivos creados

  • StockWatcher.gwt.xml
    GWT module definition
  • StockWatcher.html
    host page
  • StockWatcher.css
    application style sheet
  • web.xml
    Java web application descriptor
  • StockWatcher.javaGWT entry point class
  • GreetingService.java, GreetingServiceAsync.java, GreetingServiceImpl.java
    GWT sample RPC classes
  • gwt-servlet.jar
    GWT server runtime library
  • StockWatcherTest.java
    Starter test case for StockWatcher
A continuación mostraremos el código sin comunicación RPC.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">


<web-app>
  
  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>StockWatcher.html</welcome-file>
  </welcome-file-list>


</web-app>



StockWatcher.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='stockwatcher'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name='com.google.gwt.user.User'/>


  <!-- Inherit the default GWT style sheet.  You can change       -->
  <!-- the theme of your GWT application by uncommenting          -->
  <!-- any one of the following lines.                            -->
  <!-- <inherits name='com.google.gwt.user.theme.clean.Clean'/>-->
  <!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
   <inherits name='com.google.gwt.user.theme.dark.Dark'/>     


  <!-- Other module inherits                                      -->


  <!-- Specify the app entry point class.                         -->
  <entry-point class='com.google.gwt.sample.stockwatcher.client.StockWatcher'/>


  <!-- Specify the paths for translatable code                    -->
  <source path='client'/>
  <source path='shared'/>


</module>

StockWatcher.css

/** Add css rules here for your application. */

body {
  padding: 10px;
}

/* Add Stock panel */
.addPanel {
  margin: 10px 0px 15px 0px;
}

/* stock list header row */
.watchListHeader {
  background-color: #2062B8;
  color: white;
  font-style: italic;
}

/* stock list flex table */
.watchList {
  border: 1px solid silver;
  padding: 2px;
  margin-bottom:6px;
}

/* stock list Price and Change fields */
.watchListNumericColumn {
  text-align: right;
  width:8em;
}

/* stock list Remove column */
.watchListRemoveColumn {
  text-align: center;
}

/* stock list, the Remove button */
.gwt-Button-remove {
  width: 50px;
}

/* Dynamic color changes for the Change field */

.positiveChange {
  color: green;
}

.negativeChange {
  color: red;
}


StockWatcher.html

<!doctype html>
<!-- The DOCTYPE declaration above will set the    -->
<!-- browser's rendering engine into               -->
<!-- "Standards Mode". Replacing this declaration  -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout.                        -->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="StockWatcher.css">

    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title>StockWatcher</title>
    
    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript" language="javascript" src="stockwatcher/stockwatcher.nocache.js"></script>
  </head>

  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
  <body>

    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
    
    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
      <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.
      </div>
    </noscript>

    <h1>StockWatcher</h1>
    <div id="stockList"></div>

  </body>
</html>


StockWatcher,java

package com.google.gwt.sample.stockwatcher.client;

import java.util.ArrayList;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class StockWatcher implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";

/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

private VerticalPanel mainPanel = new VerticalPanel();
private FlexTable stocksFlexTable = new FlexTable();
private HorizontalPanel addPanel = new HorizontalPanel();
private TextBox newSymbolTextBox = new TextBox();
private Button addStockButton = new Button("Add");
private Label lastUpdatedLabel = new Label();
private ArrayList<String> stocks = new ArrayList<String>();


/**
* This is the entry point method.
*/
@SuppressWarnings("deprecation")
public void onModuleLoad() {

// Create table for stock data.
   stocksFlexTable.setText(0, 0, "Symbol");
   stocksFlexTable.setText(0, 1, "Price");
   stocksFlexTable.setText(0, 2, "Change");
   stocksFlexTable.setText(0, 3, "Remove");
   
   // Add styles to elements in the stock list table.
   // The the header row in the flex table displays white italic headings against a blue background.
   stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
   stocksFlexTable.addStyleName("watchList");
   stocksFlexTable.getCellFormatter().addStyleName(0, 1, "watchListNumericColumn");
   stocksFlexTable.getCellFormatter().addStyleName(0, 2, "watchListNumericColumn");
   stocksFlexTable.getCellFormatter().addStyleName(0, 3, "watchListRemoveColumn");
   // distancia entre el valor que esta dentro de la celda y los bordes de cada celda. 
   stocksFlexTable.setCellPadding(6);
   // distancia entre cada celda y el bordes de las filas y columnas de la tabla
   stocksFlexTable.setCellSpacing(1);

   
   // Add styles to addPanel
   addPanel.setStyleName("addPanel");
   
// Assemble Add Stock panel.
   addPanel.add(newSymbolTextBox);
   addPanel.add(addStockButton);
   
// Assemble Main panel.
   mainPanel.add(stocksFlexTable);
   mainPanel.add(addPanel);
   mainPanel.add(lastUpdatedLabel);
   
// Associate the Main panel with the HTML host page.
   RootPanel.get("stockList").add(mainPanel);
   
// Move cursor focus to the input box.
   newSymbolTextBox.setFocus(true);
   
   // Listen for mouse events on the Add button.
   addStockButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
addStock();
}
});
   
}

private void addStock() {

System.out.println("addStock() INICIO");
newSymbolTextBox.setFocus(true);
newSymbolTextBox.selectAll();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
//if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")){
if (!symbol.matches("^[0-9\\.]{1,10}$")){
//Window.alert("No es un valor entre 1 y 9 o letra entre A y Z. Valor ingresado: " + symbol);
Window.alert("No es un valor entre 1 y 9. Valor ingresado: " + symbol);
return;
}
if (stocks.contains(symbol)){
Window.alert("Ya existe este symbol en la tabla de stock, por favor ingrese otro");
return;
}
// Add the stock to the table.
// When you call the setText method, the FlexTable automatically creates new cells as needed; therefore, you don't need to resize the table explicitly. 
int rowCount = stocksFlexTable.getRowCount();
stocks.add(symbol);
stocksFlexTable.setText(rowCount, 0, symbol);
// Add style.
stocksFlexTable.getCellFormatter().addStyleName(rowCount, 1, "watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(rowCount, 2, "watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(rowCount, 3, "watchListRemoveColumn");
// Format the data in the Price and Change fields.
Label label = new Label();
if (Integer.parseInt(symbol) > 100){
label.setStyleName("negativeChange");
} else {
label.setStyleName("positiveChange");
}
   String harcodedPriceText = NumberFormat.getFormat("$#,##0.00").format(100);
   label.setText(harcodedPriceText);
   stocksFlexTable.setWidget(rowCount, 1, label);
// Add a button to remove this stock from the table.
Button removeButton = new Button("X");
// Add style dependent on primary style
// La renderizacion seria algo asi: <button class="gwt-Button gwt-Button-remove" tabindex="0" type="button">x</button> 
removeButton.addStyleDependentName("remove");
stocksFlexTable.setWidget(rowCount, 3, removeButton);
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int indexOf = stocks.indexOf(symbol);
stocks.remove(indexOf);
stocksFlexTable.removeRow(indexOf + 1);
}
});


System.out.println("addStock() FIN");
}
}


http://127.0.0.1:8888/StockWatcher.html?gwt.codesvr=127.0.0.1:9997





A continuación encontraremos todos los componentes GWT con sus correspondientes ejemplos. Muy muy utiles.

http://www.java2s.com/Code/Java/GWT/CatalogGWT.htm
http://code.google.com/intl/es/webtoolkit/doc/latest/RefWidgetGallery.html



Bibliografia

Conceptos básicos

http://code.google.com/intl/es-419/eclipse/docs/getting_started.html
http://code.google.com/intl/es/webtoolkit/doc/latest/tutorial/create.html

Para el capitulo de los eventos, tener en cuenta este best practice.

http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideUiHandlers.html
http://www.vogella.de/articles/GWT/article.html

I18N

http://code.google.com/intl/es/webtoolkit/doc/latest/tutorial/i18n.html

RPC

http://code.google.com/intl/es/webtoolkit/doc/latest/tutorial/clientserver.html
http://code.google.com/intl/es/webtoolkit/doc/latest/tutorial/RPC.html
http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideServerCommunication.html

Componentes (Widgets varios)

http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideUiPanels.html
http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideUiWidgets.html
http://code.google.com/intl/es/webtoolkit/doc/latest/RefWidgetGallery.html
https://sites.google.com/site/gwttutor/2-absolutepanel
http://www.java2s.com/Code/Java/GWT/CatalogGWT.htm

Organización de los proyectos

http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideOrganizingProjects.html

Conceptos útiles

http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideCodingBasicsCompatibility.html
http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideCodingBasicsHistory.html
http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideCodingBasicsFormatting.html
http://code.google.com/intl/es/webtoolkit/doc/latest/DevGuideCodingBasicsDeferred.html

Grupo de GWT para FAQ

http://groups.google.com/group/Google-Web-Toolkit

No hay comentarios:

Publicar un comentario