Label is not displayed

Asked

Viewed 642 times

2

I created a label where it would contain the status of the process of connection with the database, but it does not appear and I have no idea why this happens, already three days that I look at the code and do not know what happens, it would be great if someone would help me find the cause of this, please.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class Funcionarios extends Janela implements ActionListener{

    Connection conexao = Conectar.getConnection();
    String status = Conectar.status;

    JTextField txt_codigo, txt_nome, txt_ende, txt_tele, txt_nasc, txt_cpf, txt_carg, txt_email;
    JLabel lbl_codigo, lbl_nome, lbl_ende, lbl_tele, lbl_nasc, lbl_cpf, lbl_carg, lbl_email, lbl_status, txt_status;
    JButton btn_inserir, btn_alterar, btn_excluir, btn_consultar;

    public Funcionarios(){
        super("Funcionários", new Dimension(460, 400));
        //getContentPane().setBackground(new Color(56, 76, 244));
        setLocationRelativeTo(null);
        setLayout(null);

        // Definição do posicionamento das labels
        lbl_codigo = new JLabel("Código:");
        lbl_codigo.setBounds(10, 30, 80, 15);
        getContentPane().add(lbl_codigo);
        lbl_codigo.setForeground(Color.black);

        lbl_nome = new JLabel("Nome:");
        lbl_nome.setBounds(10, 60, 80, 15);
        getContentPane().add(lbl_nome);
        lbl_nome.setForeground(Color.black);

        lbl_ende = new JLabel("Endereço:");
        lbl_ende.setBounds(10, 90, 80, 15);
        getContentPane().add(lbl_ende);
        lbl_ende.setForeground(Color.black);

        lbl_tele = new JLabel("Telefone:");
        lbl_tele.setBounds(10, 120, 60, 15);
        getContentPane().add(lbl_tele);
        lbl_tele.setForeground(Color.black);

        lbl_nasc = new JLabel("Data de nascimento:");
        lbl_nasc.setBounds(10, 150, 200, 15);
        getContentPane().add(lbl_nasc);
        lbl_nasc.setForeground(Color.black);

        lbl_cpf = new JLabel("CPF:");
        lbl_cpf.setBounds(10, 180, 50, 15);
        getContentPane().add(lbl_cpf);
        lbl_cpf.setForeground(Color.black);

        lbl_carg = new JLabel("Cargo:");
        lbl_carg.setBounds(10, 210, 50, 15);
        getContentPane().add(lbl_carg);
        lbl_carg.setForeground(Color.black);

        lbl_email = new JLabel("E-mail:");
        lbl_email.setBounds(10, 240, 50, 15);
        getContentPane().add(lbl_email);
        lbl_email.setForeground(Color.black);

        // Definição do posicionamento das caixas de texto
        txt_codigo = new JTextField();
        txt_codigo.setBounds(130, 30, 150, 20);
        getContentPane().add(txt_codigo);

        txt_nome = new JTextField("");
        txt_nome.setBounds(130, 60, 150, 20);
        getContentPane().add(txt_nome);

        txt_ende = new JTextField("");
        txt_ende.setBounds(130, 90, 150, 20);
        getContentPane().add(txt_ende);

        txt_tele = new JTextField("");
        txt_tele.setBounds(130, 120, 150, 20);
        getContentPane().add(txt_tele);

        txt_nasc = new JTextField("");
        txt_nasc.setBounds(130, 150, 150, 20);
        getContentPane().add(txt_nasc);

        txt_cpf = new JTextField();
        txt_cpf.setBounds(130, 180, 150, 20);
        getContentPane().add(txt_cpf);

        txt_carg = new JTextField("");
        txt_carg.setBounds(130, 210, 150, 20);
        getContentPane().add(txt_carg);

        txt_email = new JTextField("");
        txt_email.setBounds(130, 240, 150, 20);
        getContentPane().add(txt_email);

        // Definição do posicionamento dos botões
        btn_inserir = new JButton("Cadastrar");
        btn_inserir.setBounds(10, 320, 100, 30);
        getContentPane().add(btn_inserir);

        btn_alterar = new JButton("Alterar");
        btn_alterar.setBounds(120, 320, 100, 30);
        getContentPane().add(btn_alterar);

        btn_excluir = new JButton("Excluir");
        btn_excluir.setBounds(230, 320, 100, 30);
        getContentPane().add(btn_excluir);

        btn_consultar = new JButton("Consultar");
        btn_consultar.setBounds(340, 320, 100, 30);
        getContentPane().add(btn_consultar);

        // Posição do status
        lbl_status = new JLabel("Status:");
        lbl_status.setBounds(10, 280, 50,15);
        getContentPane().add(lbl_status);
        lbl_status.setForeground(Color.black);

        txt_status = new JLabel(this.status);
        txt_status.setForeground(Color.RED);
        txt_status.setBounds(10, 280, 200, 20);

        // Atribuindo eventos aos botões
        btn_inserir.addActionListener(this);
        btn_alterar.addActionListener(this);
        btn_excluir.addActionListener(this);
        btn_alterar.addActionListener(this);
    }

    public static void main(String args[]) {
        Funcionarios tela;
        tela = new Funcionarios();
        tela.setVisible(true);
        tela.setResizable(false);
    }

    void LimpaCampos() {
        txt_codigo.setText("");
        txt_nome.setText("");
        txt_ende.setText("");
        txt_tele.setText("");
        txt_nasc.setText("");
        txt_cpf.setText("");
        txt_carg.setText("");
        txt_email.setText("");
    }

    public void actionPerformed(ActionEvent botao) {
        if(botao.getSource() == btn_inserir) {
            boolean ok;
            ok = gravaFuncionarios();
            if(ok) {
                LimpaCampos();
                txt_status.setText("Dados gravados.");
            }
            else {
                txt_status.setText("Erro ao gravar");
            }
        }
        if(botao.getSource() == btn_excluir) {
            boolean ok;
            ok = excluirFuncionarios();
            if(ok) {
                LimpaCampos();
                txt_status.setText("Registro excluído.");
            }
            else {
                txt_status.setText("Código não cadastrado.");
                LimpaCampos();
            }
        }

        if (botao.getSource()== btn_alterar) {
            boolean ok ;
            ok = alterarFuncionarios();
            if (ok){
                txt_status.setText("Registro Alterado");
            }else{
                txt_status.setText("Código não encontrado");
            }
            LimpaCampos();
        }
        if(botao.getSource() == btn_consultar ){
            boolean ok ;
            ok = consultaFuncionarios();
            if ( ok ){
                txt_status.setText("");
            }else{
                txt_status.setText("Código não cadastrado");
                LimpaCampos();
            }

        }

    }

    boolean gravaFuncionarios() {
        boolean ok = true;
        //int vCodigo = Integer.parseInt(txt_codigo.getText());
        String vNome = txt_nome.getText();
        String vEnde = txt_ende.getText();
        String vTele = txt_tele.getText();
        String vNasc = txt_nasc.getText();
        String vCPF = txt_cpf.getText();
        String vCargo = txt_carg.getText();
        String vEmail = txt_email.getText();

        String vSQL;
        vSQL = "INSERT INTO FUNCIONARIOS VALUES('"+ vNome +"', '"+ vEnde +"', '"+ vTele +"', '"+ vNasc +"', '"+ vCPF +"', '"+ vCargo +"', '"+ vEmail +"')";

        try {
            Statement st = conexao.createStatement();
            st.executeUpdate(vSQL);
        }
        catch(SQLException erro) {
            ok = false;
        }
        return ok;
    }

    boolean excluirFuncionarios() {
        boolean ok = true;

        int vCodigo = Integer.parseInt(txt_codigo.getText());

        String vSQL;
        vSQL = "DELETE FROM FUNCIONARIOS WHERE CodFunc=" + vCodigo;

        try {
            Statement st = conexao.createStatement();
            st.executeUpdate(vSQL);
        }
        catch(SQLException erro) {
            ok = false;
        }
        return ok;
    }

    boolean alterarFuncionarios() {
        boolean ok = true;
        int vCodigo = Integer.parseInt(txt_codigo.getText());
        String vNome = txt_nome.getText();
        String vEnde = txt_ende.getText();
        String vTele = txt_tele.getText();
        String vNasc = txt_nasc.getText();
        String vCPF = txt_cpf.getText();
        String vCargo = txt_carg.getText();
        String vEmail = txt_email.getText();

        String vSQL;
        vSQL = "UPDATE FUNCIONARIOS SET NomFunc='" + vNome + "', EndFunc='" + vEnde + "' TelFunc='" + vTele + "' NasFunc='" + vNasc + "' CPFFunc='" + vCPF + "' CgoFunc='" + vCargo + "' EmaFunc='" + vEmail + "'WHERE CodFunc=" + vCodigo;

        try {
            Statement st = conexao.createStatement();
            st.executeUpdate(vSQL);
        }
        catch(SQLException erro) {
            ok = false;
        }
        return ok;
    }

    boolean consultaFuncionarios(){
        boolean ok = true ;
        int vCodigo = Integer.parseInt(txt_codigo.getText());
        String sql; 

        sql = "SELECT * FROM FUNCIONARIOS WHERE CodFunc=" + vCodigo ;
        try{
            Statement st = conexao.createStatement();
            ResultSet rs = st.executeQuery(sql) ;
            if (rs.next()){
                txt_nome.setText(rs.getString("NomFunc"));
                txt_ende.setText(rs.getString("EndFunc"));
                txt_tele.setText(rs.getString("TelFunc"));
                txt_nasc.setText(rs.getString("NasFunc"));
                txt_cpf.setText(rs.getString("CPFFunc"));
                txt_carg.setText(rs.getString("CgoFunc"));
                txt_email.setText(rs.getString("EmaFunc"));
            }else{
                ok = false ; 
            }
        }catch(Exception erro){
            ok = false ;
        }
        return ok ;
    }
}

Help me please!!!!!! And thank you.

  • 1

    291 lines of code. That’s no big no. I took the liberty of editing and placing the code here.

1 answer

3


Your problem is you seem to have forgotten this:

    getContentPane().add(txt_status);

To be put right after that:

    txt_status = new JLabel(this.status);
    txt_status.setForeground(Color.RED);
    txt_status.setBounds(10, 280, 200, 20);

Also the position of this label on the screen seems to be incorrect. I think it should be this:

    txt_status.setBounds(130, 280, 200, 15);

To help you, I must also say that your program has several other problems:

  • SQL Injection.

  • Handle Swing Components Outside EDT. This can cause bugs that are difficult to track.

  • A ActionListener generic instead of using ActionListeners specific. This tends to make the code confusing and difficult to move.

  • Mixing data access code with UI code. This is bad programming practice.

  • Nomenclature of variables in disagreement with the standard.

  • You use fields with package visibility. Rarely is this what you want. I think they should be private.

  • Exceptions treatment well half mouth. You show "Unregistered code" and "Code not found" if the user did not find what he was looking for or if an error occurred in accessing the database. It is important to distinguish these two situations to avoid the user thinking that the information has disappeared from the system when actually an error occurred in connection with the database.

  • Input kludge: If the user enters a text instead of a number on txt_codigo, will pop a NumberFormatException. If he types a text too large to fit in the database in some fields, he will pop one SQLException also.

  • The field txt_codigo maybe it should be read-only, or it can mess up a lot with your database by inserting arbitrary values into it.

  • It seems to me that Conectar.status is a global variable. And you should know that using global variables is not a good practice of programming.

  • When closing the window, nothing happens. The system does not close. Maybe you have put the code to do this in the superclass Janela, but may be missing.

  • Thank you very much man, I feel like hitting the wall now, I am very new in java, thanks for the tips, I will research about all the problems and do everything possible to disappear with them. Once again, thank you.

  • @You’re welcome. Any questions, there’ll always be someone here at Stackoverflow to help. :)

  • And what would be UI code? I searched and did not find, rs

  • @Wellingtonviana UI = User Interface. That is, user interface. In your case, Swing.

  • I got it, thanks. And as for the status variable, it is in this class http://pastebin.com/YrNbbti9 which would be recommended I use instead of a global variable?

  • You may want to instantiate the class Conexao (and remove the modifier abstract) and put the status and the method getConnection() as an instance rather than a static one. This will also help you if your application can evolve to have two or more connections to the database (evolving to this when it’s already big is difficult, I tell you from experience). If you are sure to have only one connection always, you can take a look at the Singleton design pattern.

  • I’m gonna see this and, once again, thank you, you helped so much man.

Show 2 more comments

Browser other questions tagged

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