sexta-feira, 8 de agosto de 2008

Método genérico para popular um jTable direto da lista que vem do JPA

Buenas,,
É um exemplo de um método genérico pra popular um jTable a partir dos dados que vem do JPA (List através de uma query do EntityManager). Este método utiliza o net.sf.jga.swing.GenericTableModel para auxiliar na conversão. Att,


package util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.List;
import net.sf.jga.swing.GenericTableModel;

/**
*
* @author esr
*/
public class DataModel {
static public GenericTableModel getTableModel(List l) throws IntrospectionException {
GenericTableModel model = null;
if (l.size() > 0) {
Class c = l.get(0).getClass();
model = new GenericTableModel(c, l);
for (PropertyDescriptor p : java.beans.Introspector.getBeanInfo(c, Object.class).getPropertyDescriptors()) {
String s = p.getName();
s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
model.addColumn(p.getPropertyType(), s);
}
}
return model;
}
}


--------------------
exemplo de chamada:

jTable1.setModel(util.DataModel.getTableModel(lista));

terça-feira, 17 de junho de 2008

JPA List e List JSF

Adaptei um método publicado aqui para fazer a conversão genérica de um List (que é o retorno de uma consulta JPA) para um List que é utilizado pelos comboboxes no JSF. O método é um draft, pode ser otimizado, mas em fim, é uma sugestão. Penso que facilita a vida.
Para se utilizar, se passa a lista, uma o nome do campo ID (como string) e o nome do campo de descrição (também como string). O retorno é um List


public List<SelectItem> getItems(List entities, String idGetMthdName, String descGetMthdName) {
List<SelectItem> items = new Vector<SelectItem>();
try {
Method idMthd = null, nameMthd = null;
for (int i = 0; i < entities.size(); i++) {
Object entity = entities.get(i);
// On the first run, initialize reflection methods for object
if (idMthd == null) {
Class entityClass = entity.getClass();
idMthd = entityClass.getMethod(idGetMthdName, new Class[]{});
nameMthd = entityClass.getMethod(descGetMthdName, new Class[]{});
}
// Retrieve values on the
//Integer id = (Integer)idMthd.invoke(entity, new Object[]{});
String id = (String) idMthd.invoke(entity, new Object[]{});
String name = (String) nameMthd.invoke(entity, new Object[]{});
//System.out.println("id=" + id);
//System.out.println("name=" + name);
// Add key information to select item list
// System.out.println("------------------------");
SelectItem item = new SelectItem();
item.setLabel(name);
item.setValue(id.toString());
items.add(item);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Fim");
return items;
}

quarta-feira, 7 de maio de 2008

Blog Novo!!

Opa,
Blog novo!!