简体   繁体   中英

How to get rid of the nullpointerexception in jframe?

My intention is to create a login page using a Jframe. I have created the database connection class in a separate file as below and when I run the login Jframe, I get an error saying nullpointer exception.

Please assist me :)

dbConnection class ----------------------------------------------

 package vehicle_renting;

    import java.sql.*;
    import javax.swing.JOptionPane;
    public class dbConnection {

       Connection con;
       Statement stmt;
       ResultSet rs;

         public dbConnection() {}

         public void connect() {
         try {
            Class.forName("com.jdbc.mysql.Driver");
         con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vehicle_renting_1","root","qwer1234");

         } catch (Exception e) {
            e.printStackTrace();
         }   
     }
     }

And the below code is placed in the jframe source.

package vehicle_renting;


import java.sql.* ;
import javax.swing.* ;
public class Login extends javax.swing.JFrame {

    Connection conn ;
    ResultSet rs;
    PreparedStatement pst;  

    /**
     * Creates new form Login
     */
    public Login() {
        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();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        txt_username = new javax.swing.JTextField();
        txt_password = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Username");

        jLabel2.setText("Password");

        jButton1.setText("Ok");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(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()
                .addGap(110, 110, 110)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(txt_password))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(txt_username, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(44, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(143, 143, 143))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txt_username, 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(txt_password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(141, Short.MAX_VALUE))
        );

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

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



    String username=txt_username.getText();
    String password=txt_password.getText();





    String sql = "select * from login where username = ? and password = ?";
        try
        {




            pst = conn.prepareStatement(sql);
            pst.setString(1, username);                 // Passing the values to the username from the textbox
            pst.setString(2, password);                 // Passing the values to the password from the textbox
            rs = pst.executeQuery();                    // Storing the results retrieved from the query
            if (rs.next())
            {
                JOptionPane.showMessageDialog(null, "Username and Password correct");
            }
            else
            {
                JOptionPane.showMessageDialog(null, "invalid username and password");
            }


        }

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






    }                                        

    /**
     * @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 form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPasswordField txt_password;
    private javax.swing.JTextField txt_username;
    // End of variables declaration                   
}

And when I run the Jframe, it says "java.lang.NullPointerException" . I can't find the error in this. Thank you

try
        { pst = conn.prepareStatement(sql);
            pst.setString(1, username);                 // Passing the values to the username from the textbox
            pst.setString(2, password);                 // Passing the values to the password from the textbox
            rs = pst.executeQuery();                    // Storing the results retrieved from the query
            if (rs.next())
            {
                JOptionPane.showMessageDialog(null, "Username and Password correct");
            }
            else
            {
                JOptionPane.showMessageDialog(null, "invalid username and password");
            }


        }

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

I think the above code segment gives me the error. I had to edit the JOptionPane to find it out.

我想说您尚未在jframe代码中初始化属性conn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM