In this article will learn to designing and coding for Login java Frame. In-order to do so, all we need is MySql and Netbeans IDE. We will create login form which will get username and password from user and check the same details are there in MySql ‘logindatabase’. If it is there will allow to continue to user dashboard page else not.
Before we proceed, Let create a database and table, We created a table : ‘logindatabase’ with fied ‘id’, ‘username, and ‘password’ in a ‘sample’ database.
Let’s break the steps in to below
- Step 01 : Create and Design new jFrame Form
- Step 02 : Create Database Table for Login as mentioned above
- Step 03 : Create Second jFrame called ‘User Dashboard’
- Step 04 : Code Login Button click Listener
Step 01: Create Login JFrame Form
Time to code the Login Button click listener. This code will help us to check the user name and password entered by each user is available on our database record which we created on Step 02.
If record available code will allow the user into the second jFrame ‘userDashboard’ else he will get a Message only and will remain in Login page only.
Double click on Login Button.
private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","");
String sql = "Select * from logindatabase where username=? and password=?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, jTextFieldUserName.getText());
pst.setString(2, jPassword.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()){
//JOptionPane.showMessageDialog(this, "Username & Password - Matching");
UserDashboard usd = new UserDashboard();
usd.setVisible(true);
this.setVisible(false);
}else {
JOptionPane.showMessageDialog(this, "Username & Password - Not Matching");
jTextFieldUserName.setText("");
jPassword.setText("");
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
Run the Project and See how the Login Page is working. Enjoy