Problem when consulting the registered position where it shows null value

Asked

Viewed 54 times

-1

Hello I am new in programming but I am developing a code through the advanced Java course of Bradesco site and there the last part is to assemble a system, however I have a problem in the consultation screen of the registered position. I have a registration screen where you enter a position name and when pressing the button to add position it sends the name of the post q I typed to the database but it is going with Null value and when I will make the query on the query screen it does not appear the name of the position that I I typed by is going Null, I’ll send the code of the two screens.

1 job registration screen

package sistema.telas;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import sistema.BancoDeDados;
import sistema.entidades.Cargo;

public class CargosInserir extends JPanel {

    JLabel labelTitulo, labelCargo;
    JTextField campoCargo;
    JButton botaoGravar;
    
    public CargosInserir() {
        criarComponentes();
        criarEventos();
    }
    
    private void criarComponentes() {
        //Na linha 34, estamos definindo que não usaremos nenhum gerenciador de layout.
        setLayout(null);
        
        /*Nas linhas 37 a 41 estamos instanciando os componentes da tela:
         - Os componentes JLabel estão sendo inicializados com textos e alinhamentos especificos.
         - Já o componente JButton, está sendo inicializado somente com seu texto de exibição.*/
        labelTitulo = new JLabel("Cadastro de Cargo", JLabel.CENTER);
        labelTitulo.setFont(new Font(labelTitulo.getFont().getName(), Font.PLAIN, 20));
        labelCargo = new JLabel("Nome do cargo", JLabel.LEFT);
        campoCargo = new JTextField();
        botaoGravar = new JButton("Adicionar Cargo");
        
        //Na linha 46 a 49, Definimos o posicionamento e o tamanho dos componentes na tela.
        labelTitulo.setBounds(20, 20, 660, 40);
        labelCargo.setBounds(150, 120, 400, 20);
        campoCargo.setBounds(150, 140, 400, 40);
        botaoGravar.setBounds(250, 380, 200, 40);
        
        //Na linha 52 a 55, adicionamos os componentes à tela.
        add(labelTitulo);
        add(labelCargo);
        add(campoCargo);
        add(botaoGravar);
        
        //Na linha 58, tornamos á tela visivel.
        setVisible(true);
    }
    /*Nas linhas 61 a 73,  estamos definindo que, ao ser acionado, o botão
     Adicionar Cargo irá criar uma instância da entidade Cargo atribuíndo ao cargo
     o valor do texto digitado no JTextField campoCargo e por fim chamar o
     método sqlInserirCargo.*/
    private void criarEventos() {
        botaoGravar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Cargo novoCargo = new Cargo();
                novoCargo.setNome(campoCargo.getText());
            
                sqlInserirCargo(novoCargo);
            }
        });
    }
        //nas linhas 74 a 78, validamos o conteúdo do campo Nome do Cargo
        private void sqlInserirCargo(Cargo novoCargo) {
            
            //validando nome
            if(campoCargo.getText().length() <= 3 /*Caso não possua mais de 3 caractres, aparecerá a seguinte mensagem ao usuário.*/)  {
            JOptionPane.showMessageDialog(null, "Por favor, preencha o nome corretamente");
            return;
            }
        
        /*Nas linhas 86 a 106, realizamos a conexão com o banco de dados para inserir um novo cargo, de acordo com os dados que foram
        adicionados ao campo Nome do Cargo.*/
            
        //Conexão
        Connection conexao;
        //Instrução SQL
        Statement instrucaoSQL;
        //Resultados
        ResultSet resultados;
        
        try {
            //conectando ao banco de dados
            conexao = DriverManager.getConnection(BancoDeDados.stringDeConexao, BancoDeDados.usuario, BancoDeDados.senha);
            
            //criando a instrução SQL
            instrucaoSQL = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            instrucaoSQL.executeUpdate("INSERT INTO cargos (nome) VALUES ('"+novoCargo.getNome()+"')");
            
            JOptionPane.showMessageDialog(null, "Cargo adicionado com sucesso!");       
                    
        }catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao adicionar o Cargo.");
            Logger.getLogger(CargosInserir.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

now I will is sending the screen 2 q is the post query

package sistema.telas;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import sistema.BancoDeDados;
import sistema.entidades.Cargo;

//Criaremos a classe CargosConsultar a partir da linha 25, Conforme a indicação no codigo.

public class CargosConsultar extends JPanel {

    Cargo cargoAtual;
    JLabel labelTitulo, labelCargo;
    JTextField campoCargo;
    JButton botaoPesquisar, botaoEditar, botaoExcluir;
    DefaultListModel<Cargo> listasCargosModelo = new DefaultListModel();
    JList<Cargo> listaCargos;
    
    public CargosConsultar() {
        criarComponentes();
        criarEventos();
    }
    private void criarComponentes() {
        setLayout(null); // Definimos que não será usado nenhum gerenciador de layout.
        
        //Nas linhas 43 a 55, instanciamos os componentes da tela.
        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 Cargo");
        botaoEditar.setEnabled(false);
        botaoExcluir = new JButton("Excluir Cargo");
        botaoExcluir.setEnabled(false);
        listasCargosModelo = new DefaultListModel();
        listaCargos = new JList();
        listaCargos.setModel(listasCargosModelo);
        listaCargos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        
        //Nas linhas 58 a 64, definimos o posicionamento e o tamanho dos componentes na tela.
        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);
        
        //Nas linhas 67 a 72 adicionamos os componentes a tela.
        add(labelTitulo);
        add(labelCargo);
        add(campoCargo);
        add(listaCargos);
        add(botaoPesquisar);
        add(botaoEditar);
        add(botaoExcluir);
        
        //Tornando a tela visível.
        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) {
            }
        });
        /*Nas linha 95 a 100 , definimos que, ao ser acionado, o botão Excluir Cargo irá
        chamar o método sqlDeletarCargo.*/
        botaoExcluir.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sqlDeletarCargo();
            }
        });
        /*Nas 103 a 116, definimos que, ao se selecionar algum cargo na lista, este será
         armazenado na variável cargoAtual, e os botões Editar Cargo e Excluir Cargo serão habilitados. */
        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);
                }
            }
        });
    }
        /*Nas linhas 118 a 147, realizamos a conexão com o banco de dados para obtermos, por meio dele, todos os cargos
        cadastrados e adicioná-los à lista de seleção.*/
        private void sqlPesquisarCargos(String nome) {
            //Conexão
            Connection conexao;
            //Instrução SQL
            Statement instrucaoSQL;
            //Resultados
            ResultSet resultados;
            
            try {
                // Conectando ao banco de dados
                conexao = DriverManager.getConnection(BancoDeDados.stringDeConexao, BancoDeDados.usuario, BancoDeDados.senha);
                
                // Criando A intrução SQL
                instrucaoSQL = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                resultados = instrucaoSQL.executeQuery("SELECT * FROM cargos WHERE nome like '%"+nome+"%'");
                
                listasCargosModelo.clear();
                
                while (resultados.next()) {
                    Cargo cargo = new Cargo();
                    cargo.setId(resultados.getInt("id"));
                    cargo.setNome(resultados.getString("Nome"));
                    
                    listasCargosModelo.addElement(cargo);
                }
            
            }catch (SQLException ex) {
                JOptionPane.showMessageDialog(null,  "Ocorreu um erro ao consultas os Cargos.");
                Logger.getLogger(CargosInserir.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
    /*Ao ser acionado o botão Excluir Cargo irá executar o método sqlDeletarCargo. na sintaxe das linhas 149 a 171, podemos ver que esse método irá
     irá se conectar com o banco de dados e executar a instrução SQL que irá remover o cargo selecionado.*/
    private void sqlDeletarCargo() {
        
        int confirmacao = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir o Cargo "+cargoAtual.getNome()+"?", "Excluir", JOptionPane.YES_NO_OPTION);
        if(confirmacao == JOptionPane.YES_OPTION) {
            // Conexão
            Connection conexao;
            // Intrução SQL
            Statement instrucaoSQL;
            // Resultados
            ResultSet resultados;
            
            try {
                // Conectando ao banco de dados
                conexao = DriverManager.getConnection(BancoDeDados.stringDeConexao, BancoDeDados.usuario, BancoDeDados.senha);
                
                // Criando a instrução SQL
                instrucaoSQL = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                instrucaoSQL.executeUpdate("DELETE cargos WHERE id="+cargoAtual.getId()+"");
                
                JOptionPane.showMessageDialog(null, "Cargo deletado com sucesso!");
            } catch(SQLException ex) {
                JOptionPane.showMessageDialog(null, "Ocorreu um erro ao excluir o Cargo.");
                Logger.getLogger(CargosInserir.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

Also in the course shows q has to be made a Package with the name Systems.entities and within that Package is where the Cargo class is, this is where I think the problem is, because this is where the codes for the class position are located where this class is used both in the Cargosinsert class and in the Cargosconsultar class, I am sending the codes of this class Cargo...

package sistema.entidades;
public class Cargo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    public void setNome(String text) {
        // TODO Auto-generated method stub
        
    }


    public void setId(int int1) {
        // TODO Auto-generated method stub
        
    }

    public String getNome() {
        // TODO Auto-generated method stub
        return null;
    }

    public String getId() {
        // TODO Auto-generated method stub
        return null;
    }
}

I believe the error is in this null Return, which is why it is appearing blank when I press to query or when I will send the name of the post to the database it sends blank, however I have already researched and do not know how I can change this Return of getNome and getId methods, like when I typed the name of the post and clicked on register and was saved in the database correctly the name of the post I typed and went to consult on the query screen, when typing the entered name would have to appear the value registered in the database, I wonder if anyone can help me, because I am very excited and excited about this program and would like to finish this system, and before anyone say that it is database error is not because it is being sent the id data in the bank then the link is being made the problem should be in what I said or in another place that I am not seeing, if someone can help me I thank you with all my heart, a and before finishing I am using the eclipse last update so far and the program is in version of java 14...

3 answers

0


Rafael, your Cargo class has no attributes and getter methods are returning Null every time. Declare the "id" and "name" attributes in the Job class and update the access methods (getters and setters):

package sistema.entidades;

public class Cargo {
    
    private Integer id;
    private String nome;
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getNome() {
        return nome;
    }
    
    public void setNome(String nome) {
        this.nome = nome;
    }
}

With this adjustment, the title name will be saved.

0

Now when I do the job registration and I consult it shows as a result of this. system.Position@41217cf0 or some other name like this one I showed and does not show the name that was typed and in the database in the field position appears the position typed on the screen but when you see in the job query screen appears this system.Title@41217cf0 or some other name similar to that code. And as I got that part right of updating the getters and the setters, I guess that’s not going. type where I have to change, in the query class and on which line.

0

This is the lines where the getter in the query class

private void create Winds() { boot Search.addActionListener(new Actionlistener() { @Override public void actionPerformed(Actionevent e) { sqlPesquisarCargos(fieldCargo.gettext()); } });

listCargos.addListSelectionListener(new Listselectionlistener() { @Override public void valueChanged(Listselectionevent e) { cargoAtual = listCargos.getSelectedValue(); if(cargoAtual == null) { boot.setEnabled(false); botaoExcluir.setEnabled(false); }Else { boot.setEnabled(true); botaoExcluir.setEnabled(true); } } }); }

private void sqlPesquisarCargos(String name) { Connection connected; Statement instrucaoSQL; Resultset results; Try { connection = Drivermanager.getConnection(Bancodedados.stringDeConexao, Bancodedados.usuario, Bancodedados.password);

            instrucaoSQL = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

            resultados = instrucaoSQL.executeQuery("SELECT * FROM cargos WHERE nome like '%"+nome+"%'");
            
            listasCargosModelo.clear();
            
            while (resultados.next()) {
                Cargo cargo = new Cargo();
                cargo.setId(resultados.getInt("id"));
                cargo.setNome(resultados.getString("nome"));
                
                listasCargosModelo.addElement(cargo);
            }
        
        }catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,  "Ocorreu um erro ao consultas os Cargos.");
            Logger.getLogger(CargosInserir.class.getName()).log(Level.SEVERE, null, ex);
        }
}

Where I have to change, who even you say q need to update the access methods...

Browser other questions tagged

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