如何摆脱jframe中的nullpointerexception?

时间:2014-03-24 17:44:02

标签: java mysql swing nullpointerexception jform

我的目的是使用Jframe创建登录页面。 我已经在一个单独的文件中创建了数据库连接类,如下所示,当我运行登录Jframe时,我收到一个错误,指出nullpointer异常。

请帮助我:)

dbConnection类--------------------------------------------- -

 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();
         }   
     }
     }

以下代码放在jframe源代码中。

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                   
}

当我运行Jframe时,它会说&#34; java.lang.NullPointerException&#34; 。我无法在此找到错误。谢谢

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);
        }

我认为上面的代码段给了我错误。我不得不编辑JOptionPane来找到它。

1 个答案:

答案 0 :(得分:0)

我说你没有在你的jframe代码中初始化属性conn