Saturday, November 19, 2011

Create A Login Form Using NetBeans IDE

How to create a login form(Java GUI Programming) through NetBeans IDE or how to use JPassword?

We will be using a text field to get the username and a password field to get the password.

1st Method
STEP-1 First of all design your form by placing the required components i.e label, text-field, password field and a button to perform the action.

Here, I have used a panel with titled border to make design look better.

STEP-2 Double-click on the 'Log In' button or right click»Events»Action»actionPerformed

STEP-3 On the Log In button's action performed event, write the following piece of code
String user=jTextField1.getText();
String pwd= new String (jPasswordField1.getPassword());
if (user.equals("yourusername") && pwd.equals("yourpassword"))
       new Home().setVisible(true);
Explanation of code- We will accept the password from the password field and store it in the variable pwd. Similarly, we will store the username in the variable user. Now, we can compare the username and password we have received to the real username and password using the if command.
Now if the username and password is correct your Home page(Java form) could be visible or you can perform any other action.

If there is only few IDs i.e only few combinations of username and password you can use If-else-if but if the IDs are more in number you have to maintain a database of usernames and their corresponding password. In such a case you can use a DBMS eg- MySQL. After that you have to create a connection between your database and your Java application.

2nd Method (Using Java Database Connectivity)

STEP-1 Same as above.

STEP-2 Add 'MySql JDBC Driver' Library in your project(Right click on project icon » Properties » Libraries » Add Library » MySql JDBC Driver)

STEP-3 Under your package and before class starts write the following codes in the source tab.
import java.sql.*;
import javax.swing.JOptionPane;
STEP-3 Now on the Login button's actionPerformed event
String sql="Select * from Table_name";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabasename","yourmysqlid","yourmysqlpassword");
/*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
STEP-4 Now we have to match our inputs of username and password with that in the database. We will use while loop for this purpose. Write the following codes under the line ResultSet rs = stmt.executeQuery(sql); and before the '}'
String user=jTextField1.getText();
String pwd= new String (jPasswordField1.getPassword());
while(rs.next()) {
String uname=rs.getString("Username");
//Username is the coloumn name in the database table
String password=rs.getString("Password");
if ((user.equals(uname)) && (pwd.equals(password)))
new Home().setVisible(true);
}
The loop will execute the number of times equal to the total of rows in the table. The Home form will open when the right combination of username and password is found.

Tips regarding Log In form

1) There are always chances that a user will enter a wrong password and username combination, in that case you should show a  message to the user regarding the same. You can use a JOptionPane for this purpose.
a- For 1st Method
You can put a else statement for displaying this error message.
else {
JOptionPane.showMessageDialog(this, "Incorrect Username or Password!");
}
b- For 2nd Method
There maybe other methods but I thought this one to be the simplest one.
Before the while loop starts declare a integer variable and initialize it with the value 0 and later in the loop we can increase its value if a right match is found. Here's the complete code that I used.
int tmp=0;
while(rs.next()) {
String uname=rs.getString("Username");
String password=rs.getString("Password");
if ((user.equals(uname)) && (pwd.equals(password))) {
new Home().setVisible(true);

tmp++;
    }
}

if (tmp==0) {
JOptionPane.showMessageDialog(null, "Username and Password not in database!");
   }
2) If you are opening a new form after a login is successful, there will be two forms on the screen as the login form will not close. So to close the login form just write dispose(); below the line new Home().setVisible(true); This will close the current form(i.e login) and there will be only one form on the screen.


3) Important properties for Password field.
Method Description Example
setBackground Sets the background color of the password field. jPasswordField1.setBackground(new java.awt.Color(255, 255, 204));
setFont Sets the font style and size for the text of the password field. jPasswordField1.setFont(new java.awt.Font("Times New Roman", 1, 12));
setEnabled The enabled state of component.True if enabled else false (Boolean) jPasswordField1.setEnabled(false);
setEchoChar This method determines which character will replace the text in display. jPasswordField1.setEchoChar('*');


Don't forget to like ThePCWizard on Facebook for latest tech news, geeky discussions and best of tech trolls. Also subscribe to RSS feeds and YouTube channel for being updated with the latest tech tutorials.

64 comments:

  1. A VERY USEFUL CONTENT BUT SEARCHING THE DATA IS NOT CLEAR I WANT TO DISPLAY THE DATA IN TABLE AFTER SEARCHIMG IT

    ReplyDelete
  2. ammo onama karana welawata labune..ahamben hambune site eka..digatama update karanna,,api up karanna help wennam oyage blog eka..good luck!!

    ReplyDelete
  3. GREAT SITE! this helps a lot

    ReplyDelete
  4. love the work around instead of the else statment for the 2nd method

    ReplyDelete
  5. great siteeeeeeee....wonderfullll

    ReplyDelete
  6. note is GREAT n thNK Q f your Note.I take this Note as my MIniPROJECt

    ReplyDelete
  7. how to add enter key function?

    ReplyDelete
  8. IT WAS VERY HELPFUL FOR ME AS I DO NOT FIND IT ANYWHERE ELSE........

    ReplyDelete
  9. i get an error saying package com.mysql does not exit. can anyone help me???

    ReplyDelete
  10. Thank you! it works! :) i have a question on how to decrypt the passwordfield with md5.. because i'm using md5 hashing in mysql database for securtiy..

    ReplyDelete
  11. though new in java programming, but i find this easy to follow because of its clarity. But how can u help me further by connecting java application that serve as an interface to a database, please

    ReplyDelete
  12. @Mozum I already have posted tutorials for that just visit the Java Programming label.

    ReplyDelete
  13. its very help full for me thanks guys very good work .........................................
    very very good work

    ReplyDelete
  14. Error is coming that " Before start of Result Set"...
    help
    .
    .
    .
    Shekhar Singh
    XII-A3 DPSG

    ReplyDelete
  15. @shekhar please be more elaborate.
    When did the error came?? run-time or compile time?
    are u using rs before initializing it??

    ReplyDelete
  16. thanks, this was helpful :)

    ReplyDelete
  17. uncompilable source code- erranoeus tree type:

    is the comment i am getting.. please help

    ReplyDelete
  18. One i click my button it shows error message please can u help me out

    ReplyDelete
  19. Hi,
    Want to really thank you for your code and very important examples.
    My question is , i have created a login screen and used your second method, I have two JFrame forms whic will display to the different users of my application based on their user profile. How do i configure the code so when the user with username ID login, they will be shown the form for a user and when admin logs in they will be shown the Form for admin.
    Thanks

    ReplyDelete
  20. i don't think u should have any problem, try this code -
    if ((user.equals(admin)) && (pwd.equals(adminpass)))
    new Admin().setVisible(true);

    else {
    while(rs.next()) {
    String uname=rs.getString("Username");
    String password=rs.getString("Password");
    if ((user.equals(uname)) && (pwd.equals(password)))
    new Home().setVisible(true);
    }
    }

    ReplyDelete
  21. Hi Rohan Makkar, thank you for your answer, that means i have to place the first if statement for the admin befor the else statement for the user right?

    ReplyDelete
  22. HI Mr Rohan, Sorry to bother oyu agai, here is my code for both the user and admin,

    String sql="Select * from users";

    try {

    Class.forName("com.mysql.jdbc.Driver");

    Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/studentrecord","root","");

    /*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */

    Statement stmt=con.createStatement();
    ResultSet rs = stmt.executeQuery(sql);

    String user=usernameField.getText();
    String pwd= new String (PasswordField.getPassword());
    String type= (String) usrTypeBox.getSelectedItem();

    int tmp=0;
    while(rs.next()) {
    String uname=rs.getString("Username");
    String password=rs.getString("Password");
    String utype=rs.getString("type");
    String Atype=rs.getString("type");

    if ((user.equals(uname)) && (pwd.equals(password)) &&(type.equals(utype))) {
    new UserTask().setVisible(true);
    dispose();

    if ((user.equals(uname)) && (pwd.equals(password)) &&(type.equals(Atype))) {
    new AdminTask().setVisible(true);
    dispose();

    tmp++;
    }
    }
    }
    if (tmp==0) {
    JOptionPane.showMessageDialog(null, "Username and Password not in database!");
    }

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

    }



    My stress now is where do i place the admin code in beetween so each opens based on their username and password?
    I do really appreciate.
    Thanks

    ReplyDelete
  23. Sorry bothering you again, it seams the answer is for the first method, can it work for the second method with multiple users and that tha database? Cos i'm using a database for the usernames and passwords.
    Thanks

    ReplyDelete
  24. this code very helpful for me..
    but i would like to know how if i want to use back the username at the login in the next page.
    for example, when the user with username 12345 login, they will be shown the form for a user with the username 12345 in that form.
    hope i can get the answer.
    thanks

    ReplyDelete
  25. Thanks bro it is works fine -

    ReplyDelete
  26. its building sucessfully bt.. isn't displaying the form or performing any tasks.. further. :(

    ReplyDelete
  27. Bro notes are very useful but small question, if i'm using the 1st method stated above and using the else statement where should i put dispose(); to dispose the first form?

    ReplyDelete
  28. @onkar
    Check that you have something like this in your code - java.awt.EventQueue.invokeLater(new Runnable() {

    public void run() {
    new YourFormName().setVisible(true);
    }
    });

    Also, make sure that your form is not placed under a [default package]

    if still not get it right, try right click your project>Clean and Build

    ReplyDelete
  29. @JayPrem
    You could dispose the form if the right combination is found i.e in the if statement below the line new Home().setVisible(true);

    ReplyDelete
  30. Got it bro thankz... any tips on making a tabbed gui??

    ReplyDelete
  31. hi rohan bhai,
    i have doubt in this code,
    "
    String user=jTextField1.getText();
    String pwd= new String (jPasswordField1.getPassword());
    while(rs.next()) {
    String uname=rs.getString("Username");
    //Username is the coloumn name in the database table
    String password=rs.getString("Password");
    if ((user.equals(uname)) && (pwd.equals(password)))
    new Home().setVisible(true);
    }
    "
    Here in 1st getString method it is "Username" but you have written "Column name" in comment, so if it column name then what is Password?
    I m really confused in this ,please explain me.

    ReplyDelete
    Replies
    1. Let me try to be more clear

      First we are getting username and password from the user in the variables user and pwd. Then we are getting username and password from each row from our mysql table and then storing them in variables uname and password. Finally, we are checking that if the user and pwd combination matches with any uname and password combination in any row of the table, if yes then we open the Home JFramForm.

      Delete
  32. thank you, now it is working...
    Can you make 2 more topics in your "java programming" section?
    1. Java Data Base Connectivity ,But this time with online host, means remote db.....so that we can use .jar from anywhere(if connected through net)
    2. A simple java GUI application for sending sms through fullonsms, way2sms....etc, as you can see such apps are available in android,j2me..etc

    ReplyDelete
  33. thanks.. i have created log in page using this coding

    ReplyDelete
  34. it really nice we learn login has a beginner

    ReplyDelete
  35. i want to how to use arraylist in the multiple forms and transefor data one class to anethor class and here must we write in the javabeans inside only and that data using in the servlet(controler) so please help me

    ReplyDelete
    Replies
    1. i m not getting getpassword()

      Delete
    2. helo , i m using netbeans for making a school project.

      i hve a password field , But when i use String S =new String(pass.getPassword());
      System.out.println(S);

      there is no output hence , login never happens ?????

      Delete
    3. Are you sure your passwordfield name is pass?? Either the field's name is different or you have initialized your PasswordField

      Delete
  36. dear sir,
    i have a doubt...
    correct output is getting when we enter same username which is in database and wrong password...
    but
    if we are entering wrong user name which is not in the database....
    am not getting any output..can you help me..

    ReplyDelete
  37. thanks, nice help

    ReplyDelete
  38. Hai plz tell me how to check the user is admin or normal user?
    its urgent

    ReplyDelete
  39. how to insert username and password into mysql database?the value for username and password is taken from textfield and password from netbeans.

    ReplyDelete
  40. dear can you help me how can i create an ireport

    ReplyDelete
  41. anybody help me to desin a login page

    ReplyDelete
  42. Thank you for this tut! It's very helpful! Keep on!

    ReplyDelete
  43. Hey..i have a doubt...i have created the login form in the same as you told..but i do'nt want another window to be opened when i press "login" button..instead the next frame should be opened in the same window. Wat could be the code for it ?

    ReplyDelete
  44. thank a lot for this tut!!!!

    ReplyDelete
  45. @rohan makkar
    sir can u give me a source code of login page that can set his name in database at one frame or jtextfield at that frame after logging in his username and password.

    ReplyDelete
  46. It says "Uncompliable souce code -'catch' without 'try'" when I click on log in. Please help.

    ReplyDelete
    Replies
    1. Go through the article again, you must have missed a step.

      Delete
  47. hi can u help me. this my code

    String sql="select * from login";
    try{
    String user = txtusername.getText();
    String pwd = new String (jPass_userpass.getPassword());
    String type =(String)jComboBox1.getSelectedItem();

    int tmp=0;
    while(rs.next()) {
    String uname=rs.getString("username");
    String pass=rs.getString("userpas");
    String utype=rs.getString("type");
    String Atype=rs.getString("type");

    if ((user.equals(uname)) && (pwd.equals(pass)) &&(type.equals(utype))) {
    new monthlyreport().setVisible(true);
    dispose();

    if ((user.equals(uname)) && (pwd.equals(pass)) &&(type.equals(Atype))) {
    new cmbJFrame().setVisible(true);
    dispose();

    tmp++;
    }
    }
    }
    if (tmp==0) {
    JOptionPane.showMessageDialog(null, "Username and Password not in database!");
    }

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

    im using derby database, I have two jtextbox and one jcombobox.
    i want login with user level... help me pls... thankz and advance


    ReplyDelete
  48. how to use jdatechooser i cannot save to database using jdatechooser.

    ReplyDelete
  49. could you please tell me if it is possible to store images in the database corresponding to each user and display it in the form and manipulate the image? this is somewhat similar to the thing which is done in city union bank net banking. but i'm using a single image instead of four. the user has to select a particular portion of the image to be authenticated.

    ReplyDelete
  50. Thank you very much for this coding!!!! I had gone through many codes for login but it didn't work... but this code is working.... again and again thanks a lot !!!

    ReplyDelete
  51. Man thaks a lot you made my day ,saved my project THANKS A THANKS ALOTTTTTTTTTTTTTTTTTTTTTTT

    ReplyDelete
  52. Pls am working on Pharmacy management system and my problem is I want to link SignUp to database. pls I will be grateful if you can help me code to link database with signup. am using netbeans.
    Kreztle@gmail.com

    ReplyDelete