I have the problem that my program returns an error, which I don't know why it occurs, when collecting data from a JTable
selected row and passing it to a series of JTextField
, the error produced is this:
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
I attach code where I load the data in the textField
private void btModificarActionPerformed(java.awt.event.ActionEvent evt) {
int rowIndex = tabla.getSelectedRow();
dni = String.valueOf(tabla.getValueAt(rowIndex,0));
nombre = String.valueOf(tabla.getValueAt(rowIndex,1));
ciudad = String.valueOf(tabla.getValueAt(rowIndex,2));
tfDni.setText(dni);
tfNombre.setText(nombre);
tfCiudad.setText(ciudad);
btInsertar.setEnabled(false);
btBorrar.setEnabled(false);
btListado.setEnabled(false);
}
Here I call the modification:
private void btAceptarActionPerformed(java.awt.event.ActionEvent evt) {
modificar();
}
Here if I make the modification:
public void modificar(){
int rowIndex = tabla.getSelectedRow();
try{
String dni = String.valueOf(tabla.getValueAt(rowIndex, 0));
String nombre = String.valueOf(tabla.getValueAt(rowIndex, 1));
String ciudad = String.valueOf(tabla.getValueAt(rowIndex, 2));
String sql = "update clientes set nombre='"+nombre+"',ciudad='"+ciudad+"' where dni='"+dni+"'";
/*PARA HACER QUE EL UPDATE COJA LOS VALORES DEL CAMPO DE TEXTO, HABRÍA QUE PASARLE EL tf.getText() que corresponda*/
mysql.ejecutar(sql);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Error al Modificar");
}
}
The constructor of the application is like this, I think the fault may be there.
public class Ventana extends javax.swing.JFrame {
MySQL mysql;
Connection con;
PreparedStatement pst;
Statement st;
DefaultTableModel modelo;
String dni;
String nombre;
String ciudad;
ResultSet rs;
public Ventana(MySQL mysql) throws SQLException {
/*INSTANCIAMOS MYSQL*/
this.mysql = new MySQL();
initComponents();
this.setVisible(true);
con = mysql.MySQLConnection("pedidos", "root", "1234");
modelo = new DefaultTableModel();
tabla.setModel(modelo);
}
Here is the photo so you can see everything
Here I attach another photo that shows all the code
Finally I attach the method where I show what is in the database and get the metadata of the columns
when choosing the row it returns me that
It returns -1, that means, in my opinion, that it has not been updated, and indeed it is.
I'm sorry for answering delay
The detail would be that you want to access the data without having selected any specific row of the jTable, to avoid this error just add an if conditioner before execution:
//Example code
Obs: An addition to the code would be to put a warning to the user that he cannot modify the data if he has not selected any record, or directly keep the button blocked until at least one record is selected.
It is because of the column number of your dni, you recovered at the beginning using column zero (0), but when you want to save in the database you are using column one (1)