Mostrando las entradas con la etiqueta gwt ext. Mostrar todas las entradas
Mostrando las entradas con la etiqueta gwt ext. Mostrar todas las entradas

martes, 31 de marzo de 2009

Como configurar GWT-EXT en NetBeans

Como configurar GWT-EXT, primero tienen que descargar el jar de Gwt-Ext y la libreria de java script que nos permite manejar widgets (Js-Ext), de este sitio http://gwt-ext.com/download/


Paso 1: El mas importante, tener ganas de terminar este pequeñito tutorial.

Paso 2: Copiamos las libreria de js-ext, pero se preguntaran donde diablos esta,
http://yogurtearl.com/ext-2.0.2.zip , la reombramos con js y la copiamos a nuestro proyecto dentro de Web Pages



Después debería estar así:


3. Agregamos el jar de gwtext.jar que esta en el zip en libreries de nuestro proyecto:

Dar click derecho en libreries, ADD jar/Folder.



4. Configuar Main.gwt.xml este archivo esta nuestro MainEntryPoint, este tiene quien es la clase principal que contiene el metodo para iniciar una aplicación gwt, debemos colocar lo siguiente tag :

<inherits name="com.gwtext.GwtExt"/>

<?xml version="1.0" encoding="UTF-8"?>
<module>
<inherits name="com.google.gwt.user.User"/>
<entry-point class="
org.yournamehere.client"/>
<!-- Do not define servlets here, use web.xml -->
<inherits name="com.gwtext.GwtExt"/>
</module>



5. Tomen un descanso

6. Configuarar las librerias de js en html o jsp donde va a estar alojada nuestra aplicación gwt, para este ejemplo sera: welcomeGwt.html, primero borren lo que tienen y copian lo siguiente:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name='gwt:module' content='org.yournamehere.Main=org.yournamehere.Main'>
<title>Main</title>
<link rel="stylesheet" type="text/css" href="js/resources/css/ext-all.css"/>
<link rel="stylesheet" type="text/css" href="js/resources/css/xtheme-gray.css" />
<script type="text/javascript" src="js/adapter/yui/yui-utilities.js"></script>
<script type="text/javascript" src="js/adapter/yui/ext-yui-adapter.js"></script>
<script type="text/javascript" src="js/ext-all.js"></script>
</head>
<body>
<script language="javascript" src="org.yournamehere.Main/org.yournamehere.Main.nocache.js"></script>
</body>
</html>

7. Llamen a ala policía escucho ruidos extraños en mi cubículo...
En este paquete org.yournamehere.client hay una clase que es la principal-> MainEntryPoint remplacen su código por este:

/*
* MainEntryPoint.java
*
* Created on 17 de junio de 2009, 06:39 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package org.yournamehere.client;

import com.google.gwt.core.client.EntryPoint;
import com.gwtext.client.core.RegionPosition;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.TabPanel;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.layout.BorderLayout;
import com.gwtext.client.widgets.layout.BorderLayoutData;

/**
*
* @author isaac
*/
public class MainEntryPoint implements EntryPoint {

/** Creates a new instance of MainEntryPoint */
public MainEntryPoint() {
}

/**
* The entry point method, called automatically by loading a module
* that declares an implementing class as an entry-point
*/
public void onModuleLoad() {

TabPanel tabPanel = new TabPanel();
tabPanel.setActiveTab(0);

Panel tab1 = new Panel();
tab1.setTitle("Bogus Tab");
tab1.setHtml(getBogusMarkup());
tab1.setAutoScroll(true);

Panel tab2 = new Panel();
tab2.setTitle("Another Tab");
tab2.setHtml(getBogusMarkup());
tab2.setAutoScroll(true);

Panel tab3 = new Panel();
tab3.setTitle("Closable Tab");
tab3.setHtml(getBogusMarkup());
tab3.setAutoScroll(true);
tab3.setClosable(true);

tabPanel.add(tab1);
tabPanel.add(tab2);
tabPanel.add(tab3);

//west panel
Panel navPanel = new Panel();
navPanel.setTitle("Navigation");
navPanel.setWidth(200);
navPanel.setCollapsible(true);

BorderLayoutData centerData = new BorderLayoutData(RegionPosition.CENTER);
centerData.setMargins(3, 0, 3, 3);

BorderLayoutData westData = new BorderLayoutData(RegionPosition.WEST);
westData.setSplit(true);
westData.setMargins(3, 3, 0, 3);
westData.setCMargins(3, 3, 3, 3);

final Window window = new Window();
window.setTitle("Layout Window");
window.setClosable(true);
window.setWidth(600);
window.setHeight(350);
window.setPlain(true);
window.setLayout(new BorderLayout());
window.add(tabPanel, centerData);
window.add(navPanel, westData);
window.setCloseAction(Window.HIDE);
window.show();
}

private static String getBogusMarkup() {
return "
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +
"Sed metus nibh, sodales a, porta at, vulputate eget, dui. " +
"In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, " +
"cursus a, fringilla vel, urna.";
}

}

Primero crea un TabPanel con tres pestañas y después es agregado ala ventana en la posición del centro atravez de:
BorderLayoutData centerData = new BorderLayoutData(RegionPosition.CENTER);
centerData.setMargins(3, 0, 3, 3);
También contiene otro panel en zona oeste que es agregado a la ventana con:
BorderLayoutData westData = new BorderLayoutData(RegionPosition.WEST);
westData.setSplit(true);
westData.setMargins(3, 3, 0, 3);
westData.setCMargins(3, 3, 3, 3);

8 . Run al archivo welcomeGwt.html despues tendran algo como esto:


Como ven es facil se pueden hacer aplicaciones bastantes vistosas, ademas de ser rapidas, depues explicare como comunicar estas GUI mediante RPC con aplicaciones cliente servidor...

Continuara

ComboBox remoto con GWT-EXT (json,jsp) con Java

Bueno supongamos que tenemos una tabla en alguna bd, y lo único que nos interesa es hacer un combobox que muestre un nombre y que tenga como value una clave:

sql:
select cvetpocit,nomtpocit from reftpocit

el modelo seria algo como esto:

/**
*
* @author isaac
*/
public class Citacion {

private String cve;
private String nombre;

public String getCve() {
return cve;
}
public void setCve(String cve) {
this.cve = cve;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}

el contenedor hecho con una conexion jdbc de java:


import conexion.connectionSelGWT;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import xxx.xxx.client.referencia.modelo.Citacion;

/**
*
* @author isaac
*/

public class ContenedorTpoCitacion {

private Connection conexion;
private Statement instruccion;

public ContenedorTpoCitacion() throws SQLException {
connectionSelGWT conectaBase = new connectionSelGWT();
conexion = conectaBase.conectBase();
}

public List<Citacion> getTpoCitacion() throws SQLException{
List<Citacion> list = new ArrayList<Citacion>();
String query = "select cvetpocit,nomtpocit from reftpocit";
instruccion = conexion.createStatement();
ResultSet resultados2 = instruccion.executeQuery(query);
while (resultados2.next()) {
Citacion citacion = new Citacion();
citacion.setCve(resultados2.getString(1));
citacion.setNombre(resultados2.getString(2));
list.add(citacion);
}
resultados2.close();
conexion.close();
return list;
}

}


Esta es clase de la conexion aunque pueden ocupar la suya, despues voy a hacer un ejemplo con hibernate:


import java.sql.*;
import java.util.Vector;


/**
* A Class class.
*


* @author Mew
*/


public class connectionSelGWT{

private Connection conexion;
public Connection conectBase(){
String URL = "jdbc:oracle:thin:@suip_o_localhost:1521:su_SID";
String userid = "su_usuario";
String password= "su_pass";
connect();
try {
conexion = DriverManager.getConnection(URL, userid, password);

}catch (SQLException E) {
return conexion=null;
}

return conexion;
}

}

El contenedor:

import conexion.connectionSelGWT;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import xxxx.xxx.referencias.modelo.Citacion;

/**
*
* @author isaac
*/
public class ContenedorTpoCitacion {
private Connection conexion;
private Statement instruccion;

public ContenedorTpoCitacion() throws SQLException {
connectionSelGWT conectaBase = new connectionSelGWT();
conexion = conectaBase.conectBase();

}

public List getTpoCitacion() throws SQLException{
List list = new ArrayList();

String query = "select cvetpocit,nomtpocit from reftpocit";

instruccion = conexion.createStatement();



ResultSet resultados2 = instruccion.executeQuery(query);
while (resultados2.next()) {
Citacion citacion = new Citacion();
citacion.setCve(resultados2.getString(1));
citacion.setNombre(resultados2.getString(2));
list.add(citacion);

}
resultados2.close();
conexion.close();
return list;
}

}

La clase que crea la estructura del json para la vista:



import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import xxx.xxx.client.referencia.modelo.Citacion;

/**
*
* @author isaac
*/
public class JsonCitacion {

public String getTpsCitacion() throws JSONException, SQLException{
ContenedorTpoCitacion con = new ContenedorTpoCitacion();
List<Citacion> list = con.getTpoCitacion();
JSONObject jsonObj = new JSONObject();
jsonObj.put("totalCount",list.size()+"");
JSONArray array = new JSONArray();
for(Citacion ci:list){
JSONObject jsonDatos = new JSONObject();
jsonDatos.put("cve",ci.getCve());
jsonDatos.put("nombre",ci.getNombre());
array.put(jsonDatos);
}

jsonObj.put("datos",array);
return jsonObj.toString();
}

public static void main(String[] args) {
JsonCitacion json = new JsonCitacion();

try {

System.out.println(json.getTpsCitacion());

} catch (JSONException ex) {

Logger.getLogger(JsonCitacion.class.getName()).log(Level.SEVERE, null, ex);

} catch (SQLException ex) {
Logger.getLogger(JsonCitacion.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


la estructura que recibiria el combo de GWT-EXT seria la siguiente:

{"totalCount":"2","datos":[{"nombre":"Periodica","cve":"1"},{"nombre":"No Periodica","cve":"2"}]}

* las xxx son paquetes con nombre de mi trabajo pero bien le pueden poner otro nombre, es para que no vean donde trabajo jijijiji+++++.

el jsp llamado jsoncitas.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="xxx.xxxx.referencias.mc.JsonCitacion"%>
<%@page import="java.sql.SQLException"%>
<%@page import="org.json.*"%>



<% JsonCitacion json = new JsonCitacion(); try { out.print(json.getTpsCitacion()); } catch (JSONException ex) { } catch (SQLException ex) { } %>

y por ultimo el combox solo pondre el codigo del combo, solo lo tienen que agregar a un panel y listo:

HttpProxy dataProxy = new HttpProxy("jsoncitas.jsp");
RecordDef recordDef = new RecordDef(new FieldDef[]{
new StringFieldDef("cve", "cve"),
new StringFieldDef("nombre", "nombre")
});
JsonReader reader4 = new JsonReader(recordDef);
reader4.setRoot("datos");
reader4.setTotalProperty("totalCount");
Store store5 = new Store(dataProxy, reader4);
store5.load();

final ComboBox cbCitacion = new ComboBox();
cbCitacion.setStore(store5);
cbCitacion.setForceSelection(true);
cbCitacion.setMinChars(1);
cbCitacion.setFieldLabel("Tipo citación");
cbCitacion.setDisplayField("nombre");
cbCitacion.setMode(ComboBox.REMOTE);
cbCitacion.setTriggerAction(ComboBox.ALL);
cbCitacion.setEmptyText("Enter tpo citación");
cbCitacion.setLoadingText("Searching...");
cbCitacion.setTypeAhead(true);
cbCitacion.setSelectOnFocus(true);
cbCitacion.setWidth(200);
cbCitacion.setHideTrigger(false);
cbCitacion.addListener(new ComboBoxListenerAdapter() {

public void onSelect(ComboBox comboBox, Record record, int index) {

String tpoCita = Integer.parseInt(record.getAsString("cve"));
MessageBox.alert("hola "+tpoCita);
}
});

y por ultimo les debe quedar algo como esto:


viernes, 23 de enero de 2009

GWT-EXT, Combo box, remoto con jsp's

Lo primero que necesitamos es crear HttpProxy y un store con la estructura de nuestro json, aunque por default este metodo se encarga de mandarle parametros con query, para este ejemplo no los tomaremos

HttpProxy dataProxy = new HttpProxy("EvaluacionJson.jsp?respuesta=revista");
RecordDef recordDef = new RecordDef(new FieldDef[]{
new StringFieldDef("clave", "clave"),
new StringFieldDef("name", "name"),});

JsonReader reader = new JsonReader(recordDef);
reader.setRoot("datos");
reader.setTotalProperty("totalCount");

Store store = new Store(dataProxy, reader, true);
store.reload();

ComboBox cbRevista = new ComboBox("Revista");

cbRevista.setStore(store);
cbRevista.setTitle("Revistas existentes");
cbRevista.setDisplayField("name");
cbRevista.setId("clave");
cbRevista.setMode(ComboBox.REMOTE);
cbRevista.setTriggerAction(ComboBox.ALL);
cbRevista.setLoadingText("Buscando...");
cbRevista.setWidth(300);
cbRevista.setEmptyText("-SELECCIONE UNA REVISTA-");
cbRevista.addListener(new ComboBoxListenerAdapter() {

public void onSelect(ComboBox comboBox, Record record, int index) {


String cveRev = record.getAsString("clave");

}
});

Podemos agregar el combo a un formpanel o aun panel, despues esta el listener del combo que escucha los eventos del combo con record.getAsString("clave") extraen el clave del combo.

El jsp :

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="org.siir.json.JsonEvaluacion"%>
<%@page import="org.json.*"%>

<%

String respuesta = request.getParameter("respuesta");

if(respuesta.equals("revista")){
JsonEvaluacion jsonEvaluacion= new JsonEvaluacion();
String stringJson="";
try {
stringJson = jsonEvaluacion.obtenRevistasCandidatas();
} catch (JSONException ex) {
out.print("{\"totalCount\":0,\"datos\":[]}");
}
out.println(stringJson);
}


%>

el json:

package org.siir.json;

import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.siir.client.modelo.hemeroteca.RevistaExistente;
import org.siir.contenedor.ContenedorRevistaCandidata;

/**
*
* @author isaac
*/
public class JsonEvaluacion {

public String obtenRevistasCandidatas() throws JSONException{
ContenedorRevistaCandidata contenedorRev= new ContenedorRevistaCandidata();
List listRev = contenedorRev.getAllRevistaExistente();
JSONObject jsonObj = new JSONObject();
jsonObj.put("totalCount", listRev.size()+"");
JSONArray array = new JSONArray();


for(RevistaExistente rev:listRev){

JSONObject jsonDatos = new JSONObject();

jsonDatos.put("name",rev.getNombreRevista());
jsonDatos.put("clave",rev.getClave()+"");


array.put(jsonDatos);
}

jsonObj.put("datos",array);


return jsonObj.toString();


}


public static void main(String[] args) throws JSONException {
JsonEvaluacion jsonEvaluacion= new JsonEvaluacion();
System.out.println(jsonEvaluacion.obtenRevistasCandidatas());
}


}
el contenedor: claro esta tienen que iniciar una session hibernate, y todo ese choro, pueden reemplazar todo esto por un contenedor con sql, y con resultset construllen la lista de RevistaExistente

public List getAllRevistaExistente() {
Session s = sF.openSession();
Transaction tx = s.beginTransaction();
Query q = s.createQuery("from RevistaExistente p where p.estadoRevista = 1" );
List respuesta=q.list();
tx.commit();
s.close();
return respuesta;
}

el modelo:

public class RevistaExistente implements IsSerializable {
private Long clave;
private String nombreRevista;

con sus getters y setters...