Display JCombobox object data in a JTextArea from the selected item

2

I wanted to show data from a client that is in a combobox inside a JTextArea, as in the following image:

Theproblemisthatonlytheinformationof"Igo Brasil" is shown, when I try to show the information of another client, this happens:

InformationfromthefirstclientpersistsinJTextArea.

Mycodethatmakesthislistingisthefollowing:

cli=(Cliente)this.cbcliente.getSelectedItem();txtareacliente.setText("Cliente: " +cli.getCliNome()+
                           "\n\nCPF: " +cli.getCliCpf()+
                           "\n\nRG: " +cli.getCliRg()+
                           "\n\nSexo: " +cli.getCliSexo());

And the DAO Client is:

package model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import model.bean.Cliente;
import model.connection.ConnectionFactory;


public class ClienteDao {

 Connection con = ConnectionFactory.getConnection();;
 String sql;
 PreparedStatement pstm;
 ResultSet rs;

 public void salvarCliente(Cliente cli) {

  try {

   sql = "INSERT INTO cliente(clinome,clicpf,clirg,clisexo,clifone)" + "VALUES(?,?,?,?,?);";

   pstm = con.prepareStatement(sql);
   pstm.setString(1, cli.getCliNome());
   pstm.setString(2, cli.getCliCpf());
   pstm.setString(3, cli.getCliRg());
   pstm.setString(4, cli.getCliSexo());
   pstm.setString(5, cli.getCliFone());
   // Para Insert, Delete e Update usa-se: pstm.execute(). 
   // Para Select, usa-se: pstm.executeQuery();
   pstm.execute();

   JOptionPane.showMessageDialog(null, "Dados inseridos com sucesso");

  } catch (Exception erro) {

   JOptionPane.showMessageDialog(null, "Erro ao salvar " + erro.getMessage());


  }
 }

 public List < Cliente > listarClientes() {

  List < Cliente > lista = new ArrayList < > ();

  try {

   sql = "SELECT clicodigo,clinome,clicpf,clirg,clifone,clisexo FROM cliente ORDER BY clicodigo;";

   pstm = con.prepareStatement(sql);
   rs = pstm.executeQuery(sql);


   while (rs.next()) {

    Cliente cli = new Cliente();

    cli.setCliCodigo(rs.getInt(1));
    cli.setCliNome(rs.getString(2));
    cli.setCliCpf(rs.getString(3));
    cli.setCliRg(rs.getString(4));
    cli.setCliFone(rs.getString(5));
    cli.setCliSexo(rs.getString(6));

    lista.add(cli);

   }


  } catch (Exception erro) {

   JOptionPane.showMessageDialog(null, "Erro ao listar " + erro.getMessage());

  }

  return lista;
 }

 public void alterarCliente(Cliente cli) {


  try {

   sql = "UPDATE cliente SET clinome=?,clicpf=?,clirg=?,clifone=?,clisexo=? WHERE clicodigo=?";

   pstm = con.prepareStatement(sql);
   pstm.setString(1, cli.getCliNome());
   pstm.setString(2, cli.getCliCpf());
   pstm.setString(3, cli.getCliRg());
   pstm.setString(4, cli.getCliFone());
   pstm.setString(5, cli.getCliSexo());
   pstm.setInt(6, cli.getCliCodigo());
   // Para Insert, Delete e Update usa-se: pstm.execute(). 
   // Para Select, usa-se: pstm.executeQuery();
   pstm.executeUpdate();

   JOptionPane.showMessageDialog(null, "Dados alterados com sucesso");

  } catch (Exception erro) {

   JOptionPane.showMessageDialog(null, "Erro ao alterar" + erro.getMessage());


  }
 }
 public void deletarCliente(Cliente cli) {


  try {

   sql = "DELETE FROM cliente WHERE clicodigo=?";

   pstm = con.prepareStatement(sql);
   pstm.setInt(1, cli.getCliCodigo());
   // Para Insert, Delete e Update usa-se: pstm.execute(). 
   // Para Select, usa-se: pstm.executeQuery();
   pstm.executeUpdate();

   JOptionPane.showMessageDialog(null, "Excluído com sucesso");

  } catch (Exception erro) {

   JOptionPane.showMessageDialog(null, "Erro ao excluir" + erro.getMessage());

  }
 }

}

Here is the Client class:

package model.bean;

public class Cliente {

    private Integer cliCodigo;
    private String cliNome;
    private String cliSexo;
    private String cliRg;
    private String cliCpf;
    private String cliFone;

    public Integer getCliCodigo() {
        return cliCodigo;
    }

    public void setCliCodigo(Integer cliCodigo) {
        this.cliCodigo = cliCodigo;
    }

    public String getCliNome() {
        return cliNome;
    }

    public void setCliNome(String cliNome) {
        this.cliNome = cliNome;
    }

    public String getCliSexo() {
        return cliSexo;
    }

    public void setCliSexo(String cliSexo) {
        this.cliSexo = cliSexo;
    }

    public String getCliRg() {
        return cliRg;
    }

    public void setCliRg(String cliRg) {
        this.cliRg = cliRg;
    }

    public String getCliCpf() {
        return cliCpf;
    }

    public void setCliCpf(String cliCpf) {
        this.cliCpf = cliCpf;
    }

    public String getCliFone() {
        return cliFone;
    }

    public void setCliFone(String cliFone) {
        this.cliFone = cliFone;
    }

    @Override
    public String toString() {
        return cliNome;
    }  
}

And here is Servicos.java, where I fill in the Combobox, with the following method:

   public void preencherComboCliente(JComboBox comboCliente){

      ClienteDao cli = new ClienteDao();

      List<Cliente> listagem3 = cli.listarClientes();

       for(Cliente c:listagem3){


        comboCliente.addItem(c);

    }
}  

Then I call the method to populate the combobox:

        servicos.preencherComboCliente(cbcliente);
    
asked by anonymous 25.04.2016 / 02:46

2 answers

2

What you want is to monitor changes in the JCombobox (I've already explained how to do this in another answer check it out there). Just add a ItemListener to your combobox, and change the itemStateChanged method:

seuJCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                // 
                if (e.getStateChange() == ItemEvent.SELECTED) {
                  Cliente cli =  (Cliente) e.getItem();
                  txtareacliente.setText("Cliente: " +cli.getCliNome()+
                   "\n\nCPF: " +cli.getCliCpf()+
                   "\n\nRG: " +cli.getCliRg()+
                   "\n\nSexo: " +cli.getCliSexo()); 
                }
            }
       });

Save : txtareacliente must be either a class field or a final field for the anonymous method to recognize its text field.

Update : To avoid cast exceptions if your combobox is editable, test the solution below that, before entering the selection, check if the item is of type Pessoa .

seuJCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                // 
                if (e.getStateChange() == ItemEvent.SELECTED) {
                  if (evt.getItem() instanceof Cliente) {
                    Cliente cli =  (Cliente) e.getItem();
                    txtareacliente.setText("Cliente: " +cli.getCliNome()+
                     "\n\nCPF: " +cli.getCliCpf()+
                     "\n\nRG: " +cli.getCliRg()+
                     "\n\nSexo: " +cli.getCliSexo()); 
                  }
               }
            }
       });
    
25.04.2016 / 04:11
2
cli = (Cliente) this.cbcliente.getSelectedItem();
txtareacliente.setText("Cliente: " +cli.getCliNome()+
                       "\n\nCPF: " +cli.getCliCpf()+
                       "\n\nRG: " +cli.getCliRg()+
                       "\n\nSexo: " +cli.getCliSexo());    
txtareacliente.updateUI();
txtareacliente.revalidate();
txtareacliente.validate();
    
25.04.2016 / 03:30