Curso de Java Netbeans Completo☕ [03.- Conectar tabla(JTable) con mysql (parte 2)]
En este tutorial vamos llenar nuestra tabla (JTable) con los datos de nuestra base de datos en mysql. Para esto vamos a inicializar la conexión cuando se cargue el constructor de nuestro formulario para después llenar la tabla desde el botón llenarTabla
Java swing: https://es.wikipedia.org/wiki/Swing_(biblioteca_gr%C3%A1fica)
Documentación de java: https://docs.oracle.com/javase/8/docs/api/
Codigo: https://github.com/programadornovato/JavaGUI/commit/24b1ccbea738a671d6560b100dd45461ee9043a1
package com.programadornovato.javagui; import javax.swing.JOptionPane; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.table.DefaultTableModel; /** * * @author eugenio */ public class Formulario extends javax.swing.JFrame { DefaultTableModel modelo=new DefaultTableModel(); Statement ejecutor=null; Connection con; String driver="com.mysql.cj.jdbc.Driver"; String user="eugenio"; String pass="123456"; String url="jdbc:mysql://localhost:3306/empleados?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; protected void cargaTabla(){ modelo.addColumn("id"); modelo.addColumn("nombre"); modelo.addColumn("puesto"); modelo.addColumn("edad"); modelo.setRowCount(0); String datos[]=new String[4]; String query="select * from empleados;"; ResultSet rs; try { ejecutor=con.createStatement(); ejecutor.setQueryTimeout(20); rs=ejecutor.executeQuery(query); while(rs.next()==true){ datos[0]=rs.getString("id"); datos[1]=rs.getString("nombre"); datos[2]=rs.getString("puesto"); datos[3]=rs.getString("edad"); modelo.addRow(datos); } tablaEmpleados.setModel(modelo); } catch (Exception e) { } } public void conectar(){ con=null; try { Class.forName(driver); con=(Connection) DriverManager.getConnection(url,user,pass); if(con!=null){ estadoCon.setText("Conexion exitosa"); } } catch (Exception e) { estadoCon.setText("Conexion no exitosa "+e); } } /** * Creates new form Formulario */ public Formulario() { initComponents(); conectar(); } /** * 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">//GEN-BEGIN:initComponents private void initComponents() { estadoCon = new javax.swing.JLabel(); llenarTabla = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tablaEmpleados = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); llenarTabla.setText("Llenar tabla"); llenarTabla.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { llenarTablaActionPerformed(evt); } }); tablaEmpleados.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null} }, new String [] { "id", "nombre", "puesto", "edad" } )); jScrollPane1.setViewportView(tablaEmpleados); 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() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(llenarTabla) .addGap(18, 18, 18) .addComponent(estadoCon, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(130, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(estadoCon, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(llenarTabla)) .addGap(28, 28, 28) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(77, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void llenarTablaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_llenarTablaActionPerformed //conectar(); cargaTabla(); }//GEN-LAST:event_llenarTablaActionPerformed /** * @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(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Formulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Formulario().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel estadoCon; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton llenarTabla; private javax.swing.JTable tablaEmpleados; // End of variables declaration//GEN-END:variables }
[Curso] Java Netbeans GUI Completo☕: https://www.youtube.com/watch?v=S0XKc_MJCS0&list=PLCTD_CpMeEKThfXo8D-RXOGu5FarO7_qv
? Instalar Netbeans 11 en Windows 10: https://www.youtube.com/watch?v=EouitrKS6Cw
? Instalar Netbeans 11 en Ubuntu con Snap [Más fácil que en windows?]: https://www.youtube.com/watch?v=LllPPV9SMzQ
? Descargar e Instalar Netbeans 11 en ubuntu 18 04: https://www.youtube.com/watch?v=tWiX3Z5t5kQ
? Netbeans Sublime Theme ?: https://www.youtube.com/watch?v=oAF2Q7mTZZM
? Editar CSS directamenete en Chrome con Netbeans: https://www.youtube.com/watch?v=HlQs0a7R2cY
Pagina de netbeans: https://netbeans.org/
Instalar MySQL? en Ubuntu 18.04: https://www.youtube.com/watch?v=hx-nGKFVixA
Instalar PhpMyAdmin en Windows 10 ⛵: https://youtu.be/36ritPuyd00
Gracias por apoyar este canal: https://www.patreon.com/programadornovato?fan_landing=true
? Facebook: https://facebook.com/ProgramadorNovatoOficial
? Twitter: https://twitter.com/programadornova
? Linkedin: https://www.linkedin.com/in/programadornovato/
? Instagram: https://www.instagram.com/programadornovato/
Ave que vuela, a la cazuela.