-1

I wanted to created a simple login form for a system I am tasked to do, however when I click the button (even without any data in the textfields) it would say "Java.lang.NullPointerException". I already tried checking my code but I am still clueless as to which is causing the problem. Here is my JFrame Login Form:

package login;
import java.sql.*;
import javax.swing.*;

public class LOGINN extends javax.swing.JFrame {
    PreparedStatement pst = null;
    ResultSet rs = null;
    MySqlConnect m2 = new MySqlConnect();

    /** Creates new form LOGINN */
    public LOGINN() {
        initComponents();
    }


    @SuppressWarnings("unchecked")

    private void btnloginActionPerformed(java.awt.event.ActionEvent evt) {
             Connection con = m2.getConnectDB();
             String SQL="Select * from login where username=? and password=?";
      try{

          rs=pst.executeQuery(SQL);
          pst.setString(1,txtusername.getText());
          pst.setString(2, txtpassword.getText());
          rs=pst.executeQuery();

           if(rs.next()){
                JOptionPane.showMessageDialog(null, "Welcome!");
                ADMIN a=new ADMIN();
                a.setVisible(true);
          }
           else{
               JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Access Denied",JOptionPane.ERROR_MESSAGE);
           }

           }
      catch(Exception e){
      JOptionPane.showMessageDialog(null, e);

      }
    }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LOGINN().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.JPanel jPanel1;
    private javax.swing.JPasswordField txtpassword;
    private javax.swing.JTextField txtusername;
    // End of variables declaration

}

Here is MySqlConnect class:

package login;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;


public class MySqlConnect {
    public Connection getConnectDB()
        {
        Connection con ;
        try{
                Class.forName("com.mysql.jdbc.Driver");
                    con = (Connection) DriverManager.getConnection("jdbc:mysql:///login", "root","");
                    return con;
            }
         catch (Exception e){
                e.printStackTrace();
                return null;
                }


    }
}

PS. I also have a Jframe form named ADMIN and I have data in my PhpMyAdmin SQL Database.

1 Answers1

0

Two points may cause this.

1.Check Database connection. (it is returning null if connection failed)

2.JOptionPane.showMessageDialog(null, "Welcome!"); Provide the Component Object instead of Null.

Hope this may helpful.

Satya Kaveti
  • 346
  • 2
  • 6