Buenas, tengo problemas con el siguiente código, espero alguien me pueda ayudar o asesorar
Antes que nada aclaro que soy nuevo en el tema, la ayuda la solicito para un proyecto de la carrera.
Requiero que el botón buscar pueda traer los datos que se esperan del JTable.
El código que estoy usando es el siguiente:
package dpoo2_u2_a3_mifv;
import Metodos.ConexionBD;
import static java.awt.image.ImageObserver.WIDTH;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/**
*
* @author IDEX2164
*/
public class RHBaja extends javax.swing.JFrame {
ConexionBD con = new ConexionBD();
Connection cn = con.Connection();
public RHBaja() {
initComponents();
MostrarDatos();
}
public void MostrarDatos (){
DefaultTableModel modelo = new DefaultTableModel();
modelo.addColumn("NumEmpleado");
modelo.addColumn("Nombre");
modelo.addColumn("Apellidos");
modelo.addColumn("Fecha de nacimiento");
modelo.addColumn("CURP");
modelo.addColumn("RFC");
modelo.addColumn("Sueldo");
modelo.addColumn("Puesto");
modelo.addColumn("Sucursal");
modelo.addColumn("Fecha de ingreso");
JTDatos.setModel(modelo);
String sql = "SELECT * FROM personal WHERE NumEmpleado LIKE '%"+txtBuscar+"' ORDER BY NumEmpleado";
String datos []= new String [10];
try {
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()){
datos[0] = rs.getString(1);
datos[1] = rs.getString(2);
datos[2] = rs.getString(3);
datos[3] = rs.getString(4);
datos[4] = rs.getString(5);
datos[5] = rs.getString(6);
datos[6] = rs.getString(7);
datos[7] = rs.getString(8);
datos[8] = rs.getString(9);
datos[9] = rs.getString(10);
modelo.addRow(datos);
}
JTDatos.setModel(modelo);
} catch (SQLException ex) {
Logger.getLogger(RHBaja.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
JLnumempleado = new javax.swing.JLabel();
txtBuscar = new javax.swing.JTextField();
btnBuscarEmpleado = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
SalirHRBaja = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
JTDatos = new javax.swing.JTable();
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dpoo2_u2_a3_mifv/menos.png"))); // NOI18N
jLabel1.setText("Baja de personal");
JLnumempleado.setText("Numero de empleado");
txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txtBuscarKeyReleased(evt);
}
});
btnBuscarEmpleado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dpoo2_u2_a3_mifv/buscar.png"))); // NOI18N
btnBuscarEmpleado.setText("Buscar");
btnBuscarEmpleado.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarEmpleadoActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dpoo2_u2_a3_mifv/archivo-bin.png"))); // NOI18N
jButton2.setText("Eliminar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
SalirHRBaja.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dpoo2_u2_a3_mifv/cerrar-sesion.png"))); // NOI18N
SalirHRBaja.setText("Salir");
SalirHRBaja.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SalirHRBajaActionPerformed(evt);
}
});
JTDatos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane1.setViewportView(JTDatos);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 634, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(SalirHRBaja))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(JLnumempleado)
.addGap(18, 18, 18)
.addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnBuscarEmpleado))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton2))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JLnumempleado)
.addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnBuscarEmpleado))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addGap(27, 27, 27)
.addComponent(SalirHRBaja)
.addContainerGap())
);
pack();
}// </editor-fold>
private void SalirHRBajaActionPerformed(java.awt.event.ActionEvent evt) {
int Salir = JOptionPane.showConfirmDialog(null, "¿Desea salir del programa?");
if (Salir == JOptionPane.YES_OPTION){
System.exit(WIDTH);
}
if (Salir == JOptionPane.NO_OPTION){
}
if (Salir == JOptionPane.CANCEL_OPTION){
JOptionPane.showMessageDialog(null, "Cancelado");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int Eliminar = JOptionPane.showConfirmDialog(null, "¿Desea eliminar el registro?");
if (Eliminar == JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "Se elimino el registro");
}
if (Eliminar == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "No se elimino registro");
}
if (Eliminar == JOptionPane.CANCEL_OPTION){
JOptionPane.showMessageDialog(null, "Cancelado");
}
}
private void btnBuscarEmpleadoActionPerformed(java.awt.event.ActionEvent evt) {
String buscar = txtBuscar.getText();
JOptionPane.showMessageDialog(null, "Se realizo busqueda");
}
private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {
}
/**
* @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(RHBaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RHBaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RHBaja.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RHBaja.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 RHBaja().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel JLnumempleado;
private javax.swing.JTable JTDatos;
private javax.swing.JButton SalirHRBaja;
private javax.swing.JButton btnBuscarEmpleado;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField txtBuscar;
// End of variables declaration
}
El Código que conecta a la BD es el siguiente:
package Metodos;
import dpoo2_u2_a3_mifv.RHBaja;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author mizzo
*/
public class ConexionBD {
public static RHBaja buscar_reg(String NumeroEmpleado) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Connection cn;
int variable=0;
Statement st;
//Se declara la conexión
public Connection Connection(){
try{
//Se manda llamar la base de datos con la cual se va a trabajar
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/proyecto?autoReconnect=true&useSSL=false","user","12345");
System.out.println("Conexión exitosa");
variable+=1;
}
catch(ClassNotFoundException | SQLException e)
{
//Muestra un diálogo de error para avisar que algo está mal
JOptionPane.showMessageDialog(null, "Favor de revisar Xampp", "Error de Conexión", JOptionPane.ERROR_MESSAGE);
//Para el programador se agrega el mensaje de salida por consola, para trabajar el error
System.out.println(e.getMessage());
}return cn;
}
Statement createStatement(){
throw new UnsupportedOperationException("No soportado");
}
PreparedStatement prepareStatement(String sql) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
PreparedStatement createStatement(String sql) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Los datos se almacenan correctamente en la base de datos, en el JTable solo realizo un select a la tabla personal, pero quiero agregar la función de buscar por numero de empleado.
Disculpen si no soy muy especifico, es la primera vez que uso stackoverflow