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.
IT WAS VERY HELPFUL FOR ME AS I DO NOT FIND IT ANYWHERE ELSE……..
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
@Mozum I already have posted tutorials for that just visit the Java Programming label.
its very help full for me thanks guys very good work …………………………………..
very very good work
Error is coming that " Before start of Result Set"…
help
.
.
.
Shekhar Singh
XII-A3 DPSG
@shekhar please be more elaborate.
When did the error came?? run-time or compile time?
are u using rs before initializing it??
uncompilable source code- erranoeus tree type:
is the comment i am getting.. please help
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);
}
}
@Andre
Yes!
Thanks bro it is works fine –
its building sucessfully bt.. isn't displaying the form or performing any tasks.. further. 🙁
@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
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?
@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);
Got it bro thankz… any tips on making a tabbed gui??
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.
thanks.. i have created log in page using this coding
it really nice we learn login has a beginner
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
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
Have you read this: Passing Value from one Form to Another in NetBeans
🙂
i m not getting getpassword()
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..
thanks, nice help
Hai plz tell me how to check the user is admin or normal user?
its urgent
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 ?????
Are you sure your passwordfield name is pass?? Either the field's name is different or you have initialized your PasswordField
how to insert username and password into mysql database?the value for username and password is taken from textfield and password from netbeans.
dear can you help me how can i create an ireport
anybody help me to desin a login page
Thank you for this tut! It's very helpful! Keep on!
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 ?
thank a lot for this tut!!!!
@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.
thnks dude 🙂
It says "Uncompliable souce code -'catch' without 'try'" when I click on log in. Please help.
Go through the article again, you must have missed a step.
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.
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 !!!
Man thaks a lot you made my day ,saved my project THANKS A THANKS ALOTTTTTTTTTTTTTTTTTTTTTTT
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
please tell me how can we attach the seven color to choose a password on registration form in java using swing please hurry up. my email is gautammithilesh15@gmail.com
How open new form or window after click on login button
new FormName().setVisible(true);
How to create new form or window after click on login button
Please I am using access database 2013 can u help me with the login
above information is very useful to me.thank you
it too good.thanks for above information
Thq bro
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.