Insert Widget into a list with Defaultlistmodel [JAVA]

Asked

Viewed 87 times

-1

all right? I am creating an application that needs to show some elements registered in a list, which I will show through Defaultlistmodel. Unfortunately within the application it recognizes the elements that were inserted but not as it should, since it does not show the name of the element but rather the path of the entity, wanted to know how do pro Deufaltlistmodel recognize my object and the elements within it as type String, not as random code. I checked if the parameters were being passed(I had it shown on the console, the elements I wanted to show) and they showed in type String , but inside the list shows as in the image below.

as it shows: inserir a descrição da imagem aqui

My code was written as follows:

public class CargosConsultar extends JPanel{
Cargo cargoAtual;
JLabel labelTitulo,labelCargo;
JTextField campoCargo;
JButton botaoPesquisar,botaoEditar,BotaoExcluir;
DefaultListModel<Cargo> listaCargosModelo = new DefaultListModel<>();
JList<Cargo> listaCargos;

public CargosConsultar ()
{
 criarComponentes();
 criarEventos();
}

private void criarComponentes() {
    setLayout(null);


    labelTitulo = new JLabel("Consulta de Cargos", JLabel.CENTER);
    labelTitulo.setFont(new Font(labelTitulo.getFont().getName(), Font.PLAIN, 20));
    labelCargo = new JLabel("Nome do Cargo",JLabel.LEFT);
    campoCargo = new JTextField();
    botaoPesquisar = new JButton("Pesquisar Cargo");
    botaoEditar = new JButton("Editar");
    botaoEditar.setEnabled(false);
    BotaoExcluir = new JButton("Excluir");
    BotaoExcluir.setEnabled(false);
    listaCargosModelo = new DefaultListModel<>();
    listaCargos = new JList();
    listaCargos.setModel(listaCargosModelo);
    listaCargos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);


    labelTitulo.setBounds(20,20,660,40);
    labelCargo.setBounds(150,120,400,20);
    campoCargo.setBounds(150,140,400,40);
    botaoPesquisar.setBounds(560,140,130,40);
    listaCargos.setBounds(150,200,400,240);
    botaoEditar.setBounds(560,360,130,40);
    BotaoExcluir.setBounds(560,400,130,40);



    add(labelCargo);
    add(labelTitulo);
    add(campoCargo);
    add(botaoPesquisar);
    add(listaCargos);
    add(botaoEditar);
    add(BotaoExcluir);

    setVisible(true);


}

private void criarEventos() {
   botaoPesquisar.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
          sqlPesquisarCargos(campoCargo.getText());
       }
   });
   botaoEditar.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {

       }
   });
   BotaoExcluir.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {

       }
   });
   listaCargos.addListSelectionListener(new ListSelectionListener() {
       @Override
       public void valueChanged(ListSelectionEvent e) {
           cargoAtual =  listaCargos.getSelectedValue();
           if(cargoAtual == null)
           {
               botaoEditar.setEnabled(false);
               BotaoExcluir.setEnabled(false);
           }
           else
           {
               botaoEditar.setEnabled(true);
               BotaoExcluir.setEnabled(true);
           }
       }
   });
}
private void sqlPesquisarCargos(String nome)
{

             //CONEXÃO 
 Connection conexao;
 //INSTRUÇÃO SQL
 Statement instrucaoSQL;
 //RESULTADOS
    ResultSet resultados;

    try {
        //conectando no banco de dados
        conexao = DriverManager.getConnection(BancoDeDados.URL_CONEXAO,BancoDeDados.USUARIO,BancoDeDados.SENHA);
        //criando a instrução SQL
        instrucaoSQL = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
       resultados = instrucaoSQL.executeQuery("SELECT * FROM cargo WHERE nome like '%"+nome+"%'");

       listaCargosModelo.clear();
       while (resultados.next())
       {
           Cargo cargo = new Cargo();
           cargo.setId(resultados.getInt("id"));
           cargo.setNome(resultados.getString("nome"));


           listaCargosModelo.addElement(cargo);
           System.out.println("nome"+ cargo.getNome());
       }



        }
     catch (SQLException ex) {
          JOptionPane.showMessageDialog(null, "Ocorreu um erro ao consultar os cargos");
       Logger.getLogger(CargosInserir.class.getName()).log(Level.SEVERE,null,ex);
    }

        }
}

2 answers

0


Try to overwrite (override) the method toString() class Cargo to make it return the value you want to appear. It should work.

This code that is currently being returned is the default return of toString(), which includes the object’s hashcode (after the @).

  • I’m still layman I’m learning, how would I create this method? @Override public String toString() . { Return getNome(); . }

  • @Pabloap Edit the question by posting the class code Cargo that I show you. That’s right, in the class code Cargo.

0

I was able to solve, just overwrite the toString() method to return only the name, thank you very much!!

I have added within my Class of entity the following code:

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

Browser other questions tagged

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