Curso de Java Netbeans Completo☕ [04.- Buscar datos de mi tabla(JTable) con mysql (parte 3)]
En este tutorial vamos buscar por nombre, puesto y edad en nuestra tabla (JTable).
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/14f2cb1d05320c80644a28bdbc60c73dfd2a1588
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) { } } protected void buscarTabla(String nombre,String puesto,String edad){ modelo.setRowCount(0); String datos[]=new String[4]; String where=" where 1=1 "; //Si el nombre no esta vacio if(nombre.isEmpty()==false){ where=where+" and nombre='"+nombre+"' "; } //Si el puesto no esta vacio if(puesto.isEmpty()==false){ where=where+" and puesto='"+puesto+"' "; } //Si la edad no esta vacio if(edad.isEmpty()==false){ where=where+" and edad='"+edad+"' "; } String query="select * from empleados "+where+" ;"; debugQuery.setText(query); 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(); porNombre = new javax.swing.JTextField(); porPuesto = new javax.swing.JTextField(); porEdad = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); btnBuscar = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); debugQuery = new javax.swing.JTextArea(); 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); jLabel1.setText("Por nombre"); jLabel2.setText("Por puesto"); jLabel3.setText("Por edad"); btnBuscar.setText("Buscar"); btnBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBuscarActionPerformed(evt); } }); debugQuery.setColumns(20); debugQuery.setRows(5); jScrollPane2.setViewportView(debugQuery); 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)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(porNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(porPuesto, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(layout.createSequentialGroup() .addComponent(porEdad, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnBuscar)))) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING))) .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)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 93, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(porNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(porPuesto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(porEdad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnBuscar)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(89, 89, 89)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void llenarTablaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_llenarTablaActionPerformed //conectar(); cargaTabla(); }//GEN-LAST:event_llenarTablaActionPerformed private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed buscarTabla(porNombre.getText(),porPuesto.getText(),porEdad.getText()); }//GEN-LAST:event_btnBuscarActionPerformed /** * @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.JButton btnBuscar; private javax.swing.JTextArea debugQuery; private javax.swing.JLabel estadoCon; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton llenarTabla; private javax.swing.JTextField porEdad; private javax.swing.JTextField porNombre; private javax.swing.JTextField porPuesto; 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/