Display Jcombobox object data in a Jtextarea from the selected item

Asked

Viewed 385 times

2

I wanted to show the data of a customer who is on a combobox inside a Jtextarea, as in the following image:

inserir a descrição da imagem aqui

The problem is that only the information of "Igo Brasil" is shown, when I try to show the information of another client, this occurs:

inserir a descrição da imagem aqui

First client information persists in the Jtextarea.

My code that makes this listing is as follows:

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

And the Clientedao 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’s 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’s Servicos.java, where I fill out 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 fill the combobox:

        servicos.preencherComboCliente(cbcliente);
  • Igo, the Igor Brasil client is already selected when you run the application?

  • Yes, he is already selected. Oh ;-; wow, I’m in the real now, really. But how would I, in addition to picking up the selected, if I change to Adriano Tavares, show only the data of Adriano Tavares, ie replace the ones that were shown

2 answers

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();
  • It did not work, he continues to show only the data of Igo Brasil, it is as if he was only getting the id of Igo Brasil in the bank, sla..

  • Edits the post and inserts more parts of the code, mainly where you create and load the cbclient object. Your client does not get’s?

  • Have, I’ll add, a moment.

  • 1

    All right, I added.

  • I didn’t find anything wrong with the data upload at Jcombobox. And apparently correctly loads the data in the combobox, since the names of the customers appear correctly. Could insert the part of your view where you display the combobox?

  • 1

    Your answer will unfortunately not solve the problem.

  • @Diegof he’s not listening to the combo object, would that be so?

  • The view code is already in the post, it is just below the second image and there is also another code in the view (in the final line of the post), where is "called" the method of filling the client’s Combobox.

  • 1

    Ingrid, that’s what listeners are for

  • Let’s imagine a Jtable with a change, say I click on such a line in Jtable and it automatically shows (arrow) the old client data to be changed, then enables the change button etc. Would it be the same logic? Just pulling the dice from a combobox.

  • @Igo see my answer.

Show 6 more comments

2


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

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()); 
                }
            }
       });

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

Update: to avoid cast exceptions if your combobox is editable, test the solution below which, before entering the selection, checks if the item is of the 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()); 
                  }
               }
            }
       });
  • 1

    Congratulations Diego, that’s right. Now when an action is executed in Jcombobox, the installed Systener will listen to this event and call the respective method that will make the change in Jtextarea.

  • 1

    Thank you very much, Diego. I saw something very similar to this in a video, but I thought it was not necessary, thank you very much! Thanks too Ingrid, for trying to help me! Thanks.

Browser other questions tagged

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