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.

 

53 thoughts on “Create A Login Form Using NetBeans IDE”

  1. 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

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

  3. @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

  4. 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?

  5. 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.

  6. 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.

  7. 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

  8. 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

  9. 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..

  10. 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 ?????

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

  12. 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 ?

  13. @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.

  14. 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.

  15. private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    String user=jTextField1.getText();
    String pwd= new String (jPasswordField1.getPassword());
    if (user.equals("yourusername") && pwd.equals("yourpassword"))
    new Home().setVisible(true);

    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);
    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);
    }
    }
    catch (Exception e){
    JOptionPane.showMessageDialog(this, e.getMessage());
    }
    }
    I STILL HAVE ISSUES ON THIS,PLEASE COULD YOU HELP OUT LOUD? THANKS.

Leave a Comment

Your email address will not be published. Required fields are marked *