Tela de Login

1 resposta
java
M

Boa Tarde,
estou fazendo uma tela de login , porem toda vez que vou logar da erro e aparece a exepitoin, não consigo achar o erro de forma alguma estou a muito tempo procurando o erro no codigo , se alguem poder ajudar, a conexao com o banco de dados ta ok,

package br.com.infox.telas;

//importando os dados do sql

import java.sql.*;

import br.com.infox.dal.ModuloConexao;

import javax.swing.JOptionPane;

public class TelaLogin extends javax.swing.JFrame {

Connection conexao = null;

PreparedStatement pst = null;

ResultSet rs = null;

//metodo logar

public void logar(){

String sql = "select * from  tbusuarios where  login_user=? and senha_user=?";
try {
  // as linhas abaixo preparam a consulta ao banco  em funcao do
  // que foi digitado nas caixas de texto . o "?" e substituto
  //conteudo das variaveis
  pst = conexao.prepareStatement(sql);
  pst.setString(1, txtusuarios.getText());
  pst.setString(2, txtsenha.getText());
  // a linha abaixo execulta a consulta ao banco de dados
  rs = pst.executeQuery();
  
  //se existir usuario e senha corespondente  entao abra a tela principal , senao exibe messagem de erro 
  if(rs.next()){
      
      TelaPrincipal principal = new TelaPrincipal();
      principal.setVisible(true);
      
      
  }else{ JOptionPane.showMessageDialog(null,"Usuario ou Senha invalida!");   
  }                 
} catch (Exception e) { JOptionPane.showMessageDialog(null, e);
}

}

public TelaLogin() {
    initComponents();
Connection conexao = ModuloConexao.conector();
//a linha abaixo serve de apoia ao status de conexao
//System.out.println(conexao);
    
    //Caso conectado vai aparecer "conectado" senao "Desconectado"
     // com texto
     /* if (conexao != null) {
        jLabel3.setText("conectado");
    } else {
        jLabel3.setText("Desconcectado");
    }
    */
     
     //para imagem
if (conexao != null) {
        lblstatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/infox/icones/1.png")));
    } else {
        lblstatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/infox/icones/02.png")));
    }
}

/**
 * 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();
    jLabel2 = new javax.swing.JLabel();
    txtusuarios = new javax.swing.JTextField();
    btnLogin = new javax.swing.JButton();
    txtsenha = new javax.swing.JPasswordField();
    lblstatus = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("System X - Login");
    setResizable(false);

    jLabel1.setText("Usuário");

    jLabel2.setText("Senha");

    txtusuarios.setText(" ");

    btnLogin.setText("Login");
    btnLogin.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnLoginActionPerformed(evt);
        }
    });

    lblstatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/infox/icones/1.png"))); // NOI18N
    lblstatus.setText(" ");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(71, 71, 71)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(txtusuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(lblstatus)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(txtsenha, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addContainerGap(78, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(30, 30, 30)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(txtusuarios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(txtsenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblstatus)
                .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(22, 22, 22))
    );

    setSize(new java.awt.Dimension(406, 227));
    setLocationRelativeTo(null);
}// </editor-fold>                        

private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                         
   
   //chamando o metodo logar
   
   logar();
    
}                                        

/**
 * @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(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new TelaLogin().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btnLogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lblstatus;
private javax.swing.JPasswordField txtsenha;
private javax.swing.JTextField txtusuarios;
// End of variables declaration

}

1 Resposta

S

Mude para SQLException no catch

E poste o a exceção que esta dando.
Faz um:

} catch (SQLException e) {
System.out.println(e.getMessage());
}

Abraços

SuperMock

Criado 14 de janeiro de 2016
Ultima resposta 14 de jan. de 2016
Respostas 1
Participantes 2