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

jtable jdialog netbeans

Estas en el tema de jtable jdialog netbeans en el foro de Java en Foros del Web. hola,tengo el siguiente codigo, que le llamo desde otra clase mediante: new frame().setVisible(true); yo creo que me deberia de crear una nueva ventana con una ...
  #1 (permalink)  
Antiguo 09/01/2012, 09:56
Avatar de godisa  
Fecha de Ingreso: noviembre-2011
Mensajes: 46
Antigüedad: 12 años, 4 meses
Puntos: 1
Pregunta jtable jdialog netbeans

hola,tengo el siguiente codigo, que le llamo desde otra clase mediante:
new frame().setVisible(true);
yo creo que me deberia de crear una nueva ventana con una tabla en la que yo creo las
columnas y las filas y voy rellenando con filas,pero no me lo hace..alguien sabe que puede pasar??
Código PHP:
public class frame extends javax.swing.JFrame {
 
    
/** Creates new form frame */
    
public frame() {
        
initComponents();
        
System.out.println("cargando...");
        
cargarTablas();
        
    }

    
/** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
@SuppressWarnings("unchecked")
    
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    
private void initComponents() {

        
scroll = new javax.swing.JScrollPane();
        
tabla = new javax.swing.JTable();

        
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
setAlwaysOnTop(true);

        
scroll.setViewportView(tabla);

        
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        
getContentPane().setLayout(layout);
        
layout.setHorizontalGroup(
            
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .
addGroup(layout.createSequentialGroup()
                .
addContainerGap()
                .
addComponent(scrolljavax.swing.GroupLayout.PREFERRED_SIZE375javax.swing.GroupLayout.PREFERRED_SIZE)
                .
addContainerGap(15Short.MAX_VALUE))
        );
        
layout.setVerticalGroup(
            
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .
addGroup(javax.swing.GroupLayout.Alignment.TRAILINGlayout.createSequentialGroup()
                .
addContainerGap(14Short.MAX_VALUE)
                .
addComponent(scrolljavax.swing.GroupLayout.PREFERRED_SIZE275javax.swing.GroupLayout.PREFERRED_SIZE)
                .
addContainerGap())
        );

        
pack();
    }
// </editor-fold>

    /**
     * @param args the command line arguments
     */
    
public static void main(String args[]) {
        
/* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        
try {
            for (
javax.swing.UIManager.LookAndFeelInfo info javax.swing.UIManager.getInstalledLookAndFeels()) {
                if (
"Nimbus".equals(info.getName())) {
                    
javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (
ClassNotFoundException ex) {
            
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVEREnullex);
        } catch (
InstantiationException ex) {
            
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVEREnullex);
        } catch (
IllegalAccessException ex) {
            
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVEREnullex);
        } catch (
javax.swing.UnsupportedLookAndFeelException ex) {
            
java.util.logging.Logger.getLogger(frame.class.getName()).log(java.util.logging.Level.SEVEREnullex);
        }
        
//</editor-fold>

        /* Create and display the form */
        
java.awt.EventQueue.invokeLater(new Runnable() {

            public 
void run() {
                new 
frame().setVisible(true);
            }
        });
    }
    
    
    public 
void cargarTablas(){
       
System.out.println("estoy cargando las tablas");
       
      
DefaultTableModel modelo = new DefaultTableModel();
 {
        
modelo.addColumn("IP");
        
modelo.addColumn("Puerto");
        
modelo.addColumn("Numero Errores");
                
modelo.addColumn("Ultima fecha Reinicio");
 }
  
tabla = new JTable(modelo);
  
scroll=new JScrollPane(tabla);
  
add(scroll,BorderLayout.CENTER);
         try
            {
                
DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
                
java.sql.Connection conexion DriverManager.getConnection ("jdbc:mysql://localhost/conexion","user""pass");
                
java.sql.Statement s conexion.createStatement();
                
ResultSet rs s.executeQuery ("select ip,numPuerto,eTotalCrc,fechaReinicio from errores");
                
Object[] fila=new Object[4];
                while (
rs.next())
                {
                    
fila[0]=rs.getString ("ip");
                    
fila[1]=rs.getString ("numPuerto");
                    
fila[2]=rs.getString("eTotalCrc");
                        
fila[3]=rs.getString("fechaReinicio");
                        
System.out.println("introduciendo"+fila[0]+" "+fila[1]+" "+fila[2]+" "+fila[3]);
                
modelo.addRow(fila);  
                        
            }
              
conexion.close();
            }
            catch (
Exception e)
            {
                
e.printStackTrace();
            }
    }
    
    
// Variables declaration - do not modify
    
public static javax.swing.JScrollPane scroll;
    public static 
javax.swing.JTable tabla;
    
// End of variables declaration

  #2 (permalink)  
Antiguo 09/01/2012, 10:08
Avatar de CapacProg  
Fecha de Ingreso: marzo-2010
Ubicación: Lima - Perú
Mensajes: 324
Antigüedad: 14 años
Puntos: 71
Respuesta: jtable jdialog netbeans

Hola, debería de colocar el tipo de exception que obtiene. Sin embargo intenta cambiar la linea:
Código Java:
Ver original
  1. DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
por la siguiente:
Código Java:
Ver original
  1. Class.forName("com.mysql.jdbc.Driver");

Luego comentas lo que sucedió.
__________________
%
El mejor guerrero no es el que triunfa siempre sino el que vuelve sin miedo a la batalla.
%
  #3 (permalink)  
Antiguo 10/01/2012, 08:10
Avatar de godisa  
Fecha de Ingreso: noviembre-2011
Mensajes: 46
Antigüedad: 12 años, 4 meses
Puntos: 1
Respuesta: jtable jdialog netbeans

aun cambiando esa linea me seguia sin mostrar la tabla,excepcion no salia ninguna.lo que pasaba es que no me creaba la tabla ni la rellenaba.
he cambiado el codigo y ahora lo que hago es esto otro:
Código PHP:
public class frame2 extends JFrame{
    public static 
MiModelo modelo = new MiModelo();
    public static 
JFrame ventana;
    public static 
JTable tabla= new JTable(modelo);


      
/* public static void main(String []args) {
            ventana = new JFrame();
            ventana.setSize(500, 500);      
            ventana.setVisible(true);
            ventana.add(tabla);
            cargarTablas();
           
        }*/
    
  
public static void cargarTablas(){
      
// System.out.println("estoy cargando las tablas");
      
      //columnas de la tabla
       
modelo.addColumn("IP");
       
modelo.addColumn("Puerto");
       
modelo.addColumn("Numero Errores Crc");
       
modelo.addColumn("Numero Errores Late Coll");
       
modelo.addColumn("Ultima fecha Reinicio (dias)");
       
       try
       {   
//conexion a la base de datos
           
Class.forName("com.mysql.jdbc.Driver"); 
       
java.sql.Connection conexion DriverManager.getConnection ("jdbc:mysql://localhost/conexion","user""pass");
       
java.sql.Statement s conexion.createStatement();
           
//consulta a la base de datos
       
ResultSet rs s.executeQuery ("select ip,numPuerto,eTotalCrc,eTotalLateColl,fechaReinicio from errores");
               
           
java.sql.ResultSetMetaData metaDatosrs.getMetaData();
           
//obtengo el numero de columnas
           
int numeroColumnasmetaDatos.getColumnCount();
           
//creo el array de etiquetas para rellenar
           
Object[] etiquetas=new Object[numeroColumnas];
           
//obtengo cada una de las etiqueras para cada columna
           
for(int i=0;i<numeroColumnas;i++){
               
//etiquetas[i]=metaDatos.getColumnLabel(i+1)+"(dias)";
              
switch (i){
                  case 
0etiquetas[i]="IP";break;
                  case 
1etiquetas[i]="Puerto";break;
                  case 
2etiquetas[i]="Errores Crc";break;
                  case 
3etiquetas[i]="Errores LateColl";break;
                  case 
4etiquetas[i]="Fecha Ultimo Reinicio (dias)";break;
               }
           }
          
//añado la fila de enunciado a la tabla       
          
modelo.addRow(etiquetas);  
          
          
//relleno las filas de las tablas
          
Object[] fila=new Object[5];
      while (
rs.next())
          {
              
fila[0]=rs.getString ("ip");
          
fila[1]=rs.getString ("numPuerto");
          
fila[2]=rs.getString("eTotalCrc");
              
fila[3]=rs.getString("eTotalLateColl");
              
fila[4]=rs.getString("fechaReinicio");
              
//System.out.println("introduciendo"+fila[0]+" "+fila[1]+" "+fila[2]+" "+fila[3]+" "+fila[4]);
          
modelo.addRow(fila);  
          }
       }catch (
Exception e){e.printStackTrace();}
  }
  
    public static 
void borrar(){   
        
        while(
modelo.getRowCount()>0)
            
modelo.removeRow(0);   
        }
}
//end class 
y la llamada es:

frame2.borrar();
frame2.ventana = new JFrame();
frame2.ventana.setSize(500, 500);
frame2.ventana.setVisible(true);
frame2.ventana.add(frame2.tabla);
frame2.cargarTablas();


ahora tengo el problema de que nose como borrar las columnas ya que si doy varias veces seguidas al boton que me crea esta
tabla me inserta 4 columnas cada vez :S
  #4 (permalink)  
Antiguo 11/01/2012, 08:39
Avatar de farfamorA  
Fecha de Ingreso: noviembre-2010
Ubicación: Lima
Mensajes: 136
Antigüedad: 13 años, 5 meses
Puntos: 24
Respuesta: jtable jdialog netbeans

No agregues las columnas dentro del método cargarTablas.
Para remover las filas hay un método más eficiente que debes ponerlo justo antes de agregar las nuevas filas.
Código Java:
Ver original
  1. public class Ejemplo{
  2. private DefaultTableModel grillaDetalle = new DefaultTableModel();
  3. private JTable jTable1 = new JTable();
  4.  
  5. public Ejemplo(){
  6. grillaDetalle.addColumn("Columna 1");
  7. grillaDetalle.addColumn("Columna 2");
  8. grillaDetalle.addColumn("Columna 3");
  9. jTable1.setModel(grillaDetalle);
  10. }
  11.  
  12.  
  13. private void cargarTabla(List<Entidad> entidades){
  14.        
  15.         grillaDetalle.getDataVector().removeAllElements();
  16.         jTable1.updateUI();
  17.        
  18.         for (Entidad entidad : entidades){
  19.             Vector<Object> fila = new Vector<Object>();
  20.             fila.addElement(entidad.getComprobante());
  21.             fila.addElement(entidad.getTipo());
  22.             fila.addElement(entidad.getNumero());
  23.             fila.addElement(entidad.getFechaEmision());
  24.             fila.addElement(entidad.getMoneda());
  25.             fila.addElement(entidad.getImporte());
  26.             grillaDetalle.addRow(fila);
  27.         }
  28.     }
  29. }
  #5 (permalink)  
Antiguo 12/01/2012, 03:28
Avatar de godisa  
Fecha de Ingreso: noviembre-2011
Mensajes: 46
Antigüedad: 12 años, 4 meses
Puntos: 1
Respuesta: jtable jdialog netbeans

okis,gracias

Etiquetas: clase, jdialog, jtable, mysql, netbeans, sql, 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 08:32.