jLabel não exibe valor setado via setText()

Olá.

Criei um sistema de login. Gostaria que após o usuário se logar, aparecesse o nome dele numa jLabel. Mas não estou conseguindo imprimir a String que contém o nome o usuário logado. Segue o código:

dashboard, onde a jLabel deveria aparecer

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;

/**
 *
 * @author André Ravazzi
 */
public class dashboard extends javax.swing.JDialog {

    /**
     * Creates new form dashboard
     */
    public dashboard(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        usuarioLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(255, 51, 51));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(usuarioLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(892, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(usuarioLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 517, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                dashboard dialog = new dashboard(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
                try {
                    
                    String usuarioLogado = login.rs.getString("nome");
                    
                    usuarioLabel.setText("Seja bem-vindo, "+usuarioLogado);
                    
                } catch (SQLException ex) {
                    Logger.getLogger(dashboard.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel usuarioLabel;
    // End of variables declaration
}

e a classe de login

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author André Ravazzi
 */
public class login extends javax.swing.JDialog {

    private static Connection conn;
    private static String query;
    public static ResultSet rs;
    private static PreparedStatement prest;
    
    
    /**
     * Creates new form login
     */
    public login(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        usuarioInput = new javax.swing.JTextField();
        pwInput = new javax.swing.JPasswordField();
        usuarioLabel = new javax.swing.JLabel();
        usuarioLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        loginButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setIcon(new javax.swing.ImageIcon("S:\\SITEDEV\\1L O G O T I P O S\\senoweb.png")); // NOI18N

        usuarioInput.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N
        usuarioInput.setForeground(new java.awt.Color(51, 51, 51));
        usuarioInput.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        usuarioInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usuarioInputActionPerformed(evt);
            }
        });

        pwInput.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N
        pwInput.setForeground(new java.awt.Color(51, 51, 51));
        pwInput.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        usuarioLabel.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
        usuarioLabel.setForeground(new java.awt.Color(226, 42, 22));
        usuarioLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        usuarioLabel.setText("Usuário:");

        usuarioLabel1.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
        usuarioLabel1.setForeground(new java.awt.Color(226, 42, 22));
        usuarioLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        usuarioLabel1.setText("Senha:");

        jLabel2.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(226, 42, 22));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Sistema de Gerenciamento de Gastos Internos");

        loginButton.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N
        loginButton.setForeground(new java.awt.Color(226, 42, 22));
        loginButton.setText("Acessar");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        closeButton.setText("Fechar");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(usuarioInput, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(usuarioLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(pwInput, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(usuarioLabel1)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(190, 190, 190)
                        .addComponent(loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(217, 217, 217)
                        .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(61, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(56, 56, 56)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(58, 58, 58)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usuarioLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usuarioLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(usuarioInput, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pwInput, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addComponent(loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(53, 53, 53))
        );

        pack();
    }// </editor-fold>                        

    private void usuarioInputActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
    }                                            

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        try {
            // TODO add your handling code here:
            
            conn = SGGI.connector.conecta();
                        
            String usuario = usuarioInput.getText();
            String senha = new String (pwInput.getPassword());  
            
            query = "SELECT * FROM usuarios WHERE usuario = '"+usuario+"' AND senha = '"+senha+"'";
            
            prest = conn.prepareStatement(query);
            rs = prest.executeQuery();
            
            if(rs.next()) {
                
                String nome = rs.getString("nome");
                String sobrenome = rs.getString("sobrenome");
                
                //fecha a tela de login
                if((nome != null)||(sobrenome != null)){
                    JOptionPane.showMessageDialog(null,"Bem vindo "+nome+" "+sobrenome);
                } else {
                    JOptionPane.showMessageDialog(null,"Bem vindo Visitante!");
                }
                
                this.dispose();
                
                //se o login retorna true, abre a dashboard
                dashboard ds = new dashboard(null, true);
                ds.setLocationRelativeTo(null);
                ds.setVisible(true);
                
            } else {
                JOptionPane.showMessageDialog(null,"Usuário ou senha incorretos");
            }
            
        } catch (Exception ex) {
            Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }                                           

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        this.dispose();
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                login dialog = new login(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton closeButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton loginButton;
    private javax.swing.JPasswordField pwInput;
    private javax.swing.JTextField usuarioInput;
    private javax.swing.JLabel usuarioLabel;
    private javax.swing.JLabel usuarioLabel1;
    // End of variables declaration                   
}

Alguma idéia da burrice que estou fazendo?

p.s.: estou usando o netBeans e já tentei colocar um setText() estático. Mas não funcionou.

Camarada, ou eu to cego ou não tem JLabel ali não.
O que eu vi foram coisas absurdas, como uma conexão com banco de dados direto na tela (argh!!!) e um JOptionPane recebendo nome.

@drsmachado,

A jLabel aparece aqui , na classe “dashboard”, linha 120:

E a tentativa de mudar o text:

String usuarioLogado = login.rs.getString("nome"); usuarioLabel.setText("Seja bem-vindo, "+usuarioLogado);

Estou usando o netbeans pra criar a interface de usuário. Vi em algumas postagens que há certo problemas em usar o netbeans pra criar UI

E quais erros absurdos vc viu? O que seria “conexão com db direto na tela”? Sou iniciante em java, gostaria de algumas dicas :wink:

grato :smiley:

1 - login.rs.getString(“nome”) está acessando qual posição do resultSet? Isso é o que gera o problema.
2 - O netbeans cria código com muita coisa desnecessária, migre urgentemente para Eclipse, faça na mão e, depois, aprenda a usar o Window Builder.
3 - Você nunca, jamais, em tempo algum, por razão que seja, deverá usar coisas para consultas a bancos de dados (como o ResultSet, Connection e etc) na mesma classe onde renderiza a interface do usuário. É uma prática horrenda.

@drsmachado

Em login.rs.getString(“nome”), na verdade, estou pegando o valor da coluna “nome” com a linha correspondente ao Login feito pelo usuário, vindos da tabela do meu DB.
Mas de qualquer jeito, mesmo eu colocando um valor estático no jLabel, essse valor não aparece. Se eu colocar usuarioLabel.setText(“teste”), não aparece o valor “teste” no jLabel quando eu rodo o programa.

Sobre as chamadas de SQL na UI, eu deveria então criar uma classe só para colocar as chamadas, e depois resgatá-las na UI? Onde eu colcoaria as query do SQL? Tem algum turorial pra me indicar (disso e também de UI no Eclipse e Window Builder)?

Grato =D

Não li seu código amigo mais uma dúvida após mudar os valores da label você experimentou da um

label.setVisible(true); 

se já fez isso desculpe mais não li seu código só peguei partes que citou nas suas citações.

[quote=brluan]Não li seu código amigo mais uma dúvida após mudar os valores da label você experimentou da um

label.setVisible(true); 

se já fez isso desculpe mais não li seu código só peguei partes que citou nas suas citações.[/quote]

Exatamente amigo…
além disso… mostre uma mensagem na tela com o nome ou um println()

String usuarioLogado = login.rs.getString("nome");    
usuarioLabel.setText("Seja bem-vindo, "+usuarioLogado);
JOptionPane.showMessageDialog(null,"Usuario logado: "+usuarioLogado);