Foros del Web » Programación para mayores de 30 ;) » Java »

Como Refrescar Jtable

Estas en el tema de Como Refrescar Jtable en el foro de Java en Foros del Web. Hola amigos buenos días tengo un gran problema al no poder refrescar mi JTable se que hay varios foros vídeos pero por mas que los ...
  #1 (permalink)  
Antiguo 19/03/2014, 10:24
 
Fecha de Ingreso: marzo-2014
Ubicación: Lima
Mensajes: 11
Antigüedad: 10 años, 1 mes
Puntos: 0
Como Refrescar Jtable

Hola amigos buenos días tengo un gran problema al no poder refrescar mi JTable se que hay varios foros vídeos pero por mas que los aplico no me actualiza mi JTable espero puedan ayudarme, les explico un poco tengo en mi clase formulario mi JFrame con todos los controles y aparte mi clase modelo con los modelos que le adjunto al JTable para que de ahi pasen a mi formulario y lo pegue nada mas.Todo estaba bien hasta que ahora que quiero refrescar mi jtable no lo hace le hice seguimiento y llena mi modelo refrescarDatos pero al terminar con todos los datos cargados llega vació a mi jtable me bota el siguiente error : Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

aquí les dejo el código para que tengan una visión mas clara:

aquí lleno mi método de insertar datos y mi modelo para que se actualice al insertar los datos, están en un jdialog se llenan al presionar el botón aceptar:

Código:
info.InsertarDatosC(var1,var2,var3,varvalue1,varvalue2,varvalue3,vare1);
try {
DefaultTableModel modelo = new DefaultTableModel();
modelo = mod.refrescarDatos(opt);
table.setModel(modelo);
System.out.println(opt);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Y este es mi modelo:


Código:
public DefaultTableModel refrescarDatos(String variable) throws SQLException {
DefaultTableModel modelotablabd = new DefaultTableModel();

for (String columna : man.LlenarTitulos(variable)) {
modelotablabd.addColumn(columna);	
}


Statement sf = conn.getConnection().createStatement();
String cad = "select * from "+variable;
ResultSet rs = sf.executeQuery(cad);
ResultSetMetaData rsMd = rs.getMetaData();
int CantidadColumnas = rsMd.getColumnCount();

Object datos[]=new Object[CantidadColumnas];
try {
while (rs.next()) {
for (int i = 0; i <CantidadColumnas; i++) {
datos[i] = rs.getObject(i + 1);
System.out.println(datos[i]);
// System.out.println("fil : "+datos[i]);
}
modelotablabd.addRow(datos);

}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return modelotablabd;
}
No se si deba usar algo como un método aparte para actualizarla...si fuera así por favor como debería hacer.
Espero en verdad puedan ayudarme necesito ayuda con urgencia estaré al tanto saludos amigos.

Última edición por MiguelP87; 19/03/2014 a las 10:41 Razón: titulo mas preciso
  #2 (permalink)  
Antiguo 19/03/2014, 11:29
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: Como Refrescar Jtable

¿En qué parte del código te lanza esa excepción? Así podremos saber cual es la variable que está ocasionando el NPE (NullPointerException).
Trata de copiar acá la excepción completa:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at mipaquete.miclaseclase:123 ... etc
  #3 (permalink)  
Antiguo 19/03/2014, 11:35
 
Fecha de Ingreso: marzo-2014
Ubicación: Lima
Mensajes: 11
Antigüedad: 10 años, 1 mes
Puntos: 0
Respuesta: Como Refrescar Jtable

Lanza lo siguiente amigo:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at formulario.JDialog.actionPerformed(JDialog.java:17 0)
at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
  #4 (permalink)  
Antiguo 19/03/2014, 11:47
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: Como Refrescar Jtable

JDialog.java:17 0
Ya ahora indícame cuál es la línea 170 de la clase formulario.JDialog.
  #5 (permalink)  
Antiguo 19/03/2014, 11:51
 
Fecha de Ingreso: marzo-2014
Ubicación: Lima
Mensajes: 11
Antigüedad: 10 años, 1 mes
Puntos: 0
Respuesta: Como Refrescar Jtable

Cita:
try {
table.setModel(mod.refrescarDatos(opt));
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
es donde lleno mi modelo
  #6 (permalink)  
Antiguo 19/03/2014, 12:03
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: Como Refrescar Jtable

Si estás usando Netbeans ¿puedes hacer un debug justo en esa línea?

En caso que no sepas utilizar el debugger, hagamos un debug a lo salvaje:
Antes de
Código Java:
Ver original
  1. table.setModel(mod.refrescarDatos(opt));
pon esto:
Código Java:
Ver original
  1. System.out.println(table == null);
  2. System.out.println(mod== null);
  3. System.out.println(opt== null);
Y copia acá lo que sale en consola.
  #7 (permalink)  
Antiguo 19/03/2014, 13:07
 
Fecha de Ingreso: marzo-2014
Ubicación: Lima
Mensajes: 11
Antigüedad: 10 años, 1 mes
Puntos: 0
Respuesta: Como Refrescar Jtable

Me sale :

true
false
false


gracias por ayudarme en serio, table no lo llenaba ya hice que mi clase JDialog se llene en formulario cunado seleccione mi raddiobutton y le de en aceptar para que me salte mi jdialog pero ahora no me sale nada....
Código:
 if(rbtAlta.isSelected()){		 					
					 JDialog jd = new JDialog(tablabd);
					if(variable.equals("Cliente")){
			 				System.out.println("\n "+"Hola Cliente");	
			 				opcion="Cliente";
			 				var="CLIENTE";		
			 			}
  #8 (permalink)  
Antiguo 19/03/2014, 13:31
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: Como Refrescar Jtable

Tu problema anterior era que tu atributo table era nulo. Ahora, para tu nuevo problema abre un nuevo hilo y procura dar más detalles (a qué clase pertenece ese método, con qué evento se dispara, qué error te da, etc).
  #9 (permalink)  
Antiguo 19/03/2014, 14:57
 
Fecha de Ingreso: marzo-2014
Ubicación: Lima
Mensajes: 11
Antigüedad: 10 años, 1 mes
Puntos: 0
Respuesta: Como Refrescar Jtable

Ok gracias te explico entonces:

Tengo mi clase formulario donde están ubicados todos mis controles la mayoría, he creado una clase JDialog que es una ventana que al seleccionar un radiobutton y darle clic en aceptar (En la clase formulario) llamo a la clase JDialog lleno mi método JDialogdinamico le paso las variables y armo mi ventana donde me muestra campos para poder ingresarlos y realizar mi insert, hasta ahi todo bien hace lo que qiero me inserta n la base de datos perfecto, ahora el problema era como refresco mi JTable?pense en ponerle un select llenar mis filas y pasarselas al modelo, se llenan tengo mi objeto con los datos pero me salio el error de que no le pasaba la tabla ahora que se la paso no se muestra mi JDialog.

No se que pueda ser aqui te paso el codigo de mi boton aceptar formulario:

Cita:
if(e.getSource()==btnAceptarM){
String tip="Alta de ",var="",opcion="",accion="",cod="";
ArrayList camps = new ArrayList();
//RadioButton Altaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
if(rbtAlta.isSelected()){
Ambc jd = new Ambc(tablabd);
if(variable.equals("Cliente")){
System.out.println("\n "+"Hola Cliente");
opcion="Cliente";
var="CLIENTE";
}
else if(variable.equals("Tasas")){
System.out.println("\n "+"Hola Tasas");
opcion="Tasas";
var="TASAS";
}
else if(variable.equals("Area")){
System.out.println("\n "+"Hola Area");
opcion="Area";
var="AREA";
}
jd.JdialogDianamico(var,opcion,tip,camps,accion);
}
Ahi ya llene mi Jdialogdinamico ahora te paso el codigo de mi boton aceptar de mi clase JDialog

Cita:
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnCancelarC){
this.dispose();
}

if(e.getSource()==btnAceptarC){

String var1=ListaCaja.get(0).getText(),var2=ListaCaja.get (1).getText(),var3=ListaCaja.get(2).getText();
String varvalue1=ListaCaja.get(0).getName(),varvalue2=Lis taCaja.get(1).getName(),varvalue3=ListaCaja.get(2) .getName();


if(ListaCaja.get(0).getText().isEmpty() || ListaCaja.get(1).getText().isEmpty() || ListaCaja.get(2).getText().isEmpty())
{
JOptionPane.showMessageDialog(null,"Se Requiere Llenar todos los Campos","Advertencia",JOptionPane.WARNING_MESSAGE) ;
}else{
switch(tipo){
case "Alta de ":
info.InsertarDatosC(var1,var2,var3,varvalue1,varva lue2,varvalue3,vare1);
try {
DefaultTableModel model = new DefaultTableModel();
model = mod.refrescarDatos(opt);
table.setModel(model);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Espero me puedas ayudar saludos.

Etiquetas: clase, jtable, refrescar, string
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 14:25.