Item in selected combobox, display data in jTable

Asked

Viewed 287 times

1

Before asking this question, I searched the forum and in several places but could not solve...

I have a combobox that already carries the names of customers, then I wanted to select the customer, and on a button ok search for this client. However, when comparing names, it falls into the message that it was not found.

 private void btnBuscaClientesActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    DefaultTableModel model = (DefaultTableModel) jTableClientes.getModel();
    String nomeCliente = comboClientes.getSelectedItem().toString();
    ConsultasDAO consulta = new ConsultasDAO();
    List<Cliente> clientes = null;
    try {
        clientes = consulta.getClientes();
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "Erro sql");
        //Logger.getLogger(TelaRelatorioGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    for (Cliente nomeClienteAtual : clientes) {
        if ((nomeCliente.toLowerCase()) == (nomeClienteAtual.getnome().toString().toLowerCase())) {
            model.addRow(new Object[]{nomeClienteAtual.getnome().toLowerCase(), nomeClienteAtual.gettelefone(), nomeClienteAtual.getrua(), nomeClienteAtual.getcomplemento()});
        } else {
            JOptionPane.showMessageDialog(null, "Cliente não encontrado");
        }
    }
}
  • Please provide a [mcve] so that it is possible to execute and test the code, and propose a solution.

1 answer

2


Comparison of java strings cannot be done with the operator == because it is a reference type but with equals. Soon this if is not correct:

if ((nomeCliente.toLowerCase()) == (nomeClienteAtual.getnome().toString().toLowerCase())) {

And correcting the if the message is not in the right place either because it is in the else. That way every time you pass by a client that is not what you are looking for a message appears.

It would be better:

int iguais = 0;
for (Cliente nomeClienteAtual : clientes) {
   if (nomeCliente.toLowerCase().equals(nomeClienteAtual.getnome().toString().toLowerCase()) {
      model.addRow(new Object[]{nomeClienteAtual.getnome().toLowerCase(), nomeClienteAtual.gettelefone(), nomeClienteAtual.getrua(), nomeClienteAtual.getcomplemento()});
      iguais++;
   } 
}

if (iguais == 0) {
   JOptionPane.showMessageDialog(null, "Cliente não encontrado");
}
  • Thank you very much! solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.