Item in comboBox selected, display data in jTable

1

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

I have a comboBox that already loads the names of the clients, there I wanted to select the client, and on a ok button to fetch that client. However, when comparing names, it falls on 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");
        }
    }
}
    
asked by anonymous 09.07.2017 / 14:46

1 answer

2

Comparison of strings in java can not 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 if , the message is also not in the correct place because it is in else . That way every time you go through a customer that is not what you are looking for, a message pops up.

It would be better this way:

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");
}
    
09.07.2017 / 15:13