Sie sind auf Seite 1von 13

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 clickEventsActionactionPerformed 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 Ifelse-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/yourdat abasename","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 setBackground setFont Description Example Sets the background color jPasswordField1.setBackground(new of the password field. java.awt.Color(255, 255, 204)); Sets the font style and size jPasswordField1.setFont(new for the text of the java.awt.Font("Times New Roman", 1, 12)); password field. The enabled state of component.True if enabled jPasswordField1.setEnabled(false); else false (Boolean) This method determines which character will jPasswordField1.setEchoChar('*'); replace the text in display.

setEnabled

setEchoChar

Passing Value from one Form to Another in NetBeans So you started learning java and someone told you can use NetBeans IDE as it will make your work easier by providing you with easy-to-use drag & drop GUI builder. Yes, it does. It really make programming easy for a beginner, by removing all coding required for the designing part. But problems crops up when you try to go advanced. And when try to for help on the web, you would really find it difficult to understand others answers. One such problem for which it would be difficult to get answer for, is passing values from one JFrame form to another. So, here's is a simple guide to help you move forward. To know how to pass value from one form to another, you need to know 'What is a Constructor?'. Constructor A Constructor is like method which has the same name as it's class. It is used to initialize the objects of that class type with a legal initial value. When you create a object of a class, the complier automatically calls it's constructor. Constructor has return value, not even void. So, we would have to overload the class's constructor in which we want to get the value. I have designed two simple JFrame forms, the first is a login screen in which a user would enter his username and password and second is a welcome screen in which we will get his username from the previous screen and display it in a label. Here's the design view of the both the forms.

Double click the Log in button to open it's actionPerformed event and paste the following code:String user=jTextField1.getText(); String pwd= new String (jPasswordField1.getPassword()); if (user.equals("admin") && pwd.equals("pass")) new Welcome(user).setVisible(true); else { JOptionPane.showMessageDialog(this, "Incorrect Username or Password!"); } As soon as you paste the code, you will see a error and NetBeans will ask you to create a constructor Welcome(java.lang.String), ignore this warning for now. As you can see, we are passing the variable user(which stores are username i.e admin) in the constructor for the Welcome form. Now, open the source tab in your Welcome form and find it's default constructor and paste/type the following code below it:public Welcome(String User) { username = User; initComponents(); } Now, declare String variable username just below your class declaration. Your code should now look like thispublic class Welcome extends javax.swing.JFrame { String username;

/** * Creates new form Welcome */ //Default constructor public Welcome() { initComponents(); }

//Our new constructor public Welcome(String User) { username = User; initComponents(); } Now, right click your welcome form and go to>Events>Window>windowOpened and use the username variable set it wherever you want! Example:userTF.setText(username); Now, go back to login form and press Shift + F6 to run your file. Enter your username and password and click login to see your name on the next screen.

You might be thinking now that why have two constructor, this is because netbeans let's us to run a single JFrame Form so if delete the old the constructor then the Runnable which is placed at the end of your code will cause you errors. Not just a simple string, you can pass any variable from one form to another and ofcourse you can pass a value further that you received from the previous class. So, let's move onto another example. Now from the welcome screen we will take an int value i.e age and a list of hobbies and pass on these values including username to a new screen. As you know we can initialize variables in the constructor, so I have declared an ArrayList under class declaration and initialized it in the constructor so that we can use it in any event we want. Here's what code looks like nowWelcome.java (only relevant part) public class Welcome extends javax.swing.JFrame { String username; ArrayList hobbies; /** * Creates new form Welcome */ //Default constructor public Welcome() { initComponents(); } //Our new constructor public Welcome(String User) { username = User; hobbies = new ArrayList();

initComponents(); } private void btnNextActionPerformed(java.awt.event.ActionEvent evt) { int age = Integer.parseInt(jTextField1.getText());

if (jCheckBox1.isSelected()) hobbies.add("Reading"); if (jCheckBox2.isSelected()) hobbies.add("Photography"); if (jCheckBox3.isSelected()) hobbies.add("Blogging"); if (jCheckBox4.isSelected()) hobbies.add("Programming");

new Details(age, hobbies, username).setVisible(true);

In details form we will initialize the 3 variables that has been passed through the constructor. We will show username and age in labels and hobbies jList component.

Details.java package demoforblog;

import java.util.ArrayList; import javax.swing.DefaultListModel;

/** * * @author Rohan */ public class Details extends javax.swing.JFrame { int age; ArrayList hobbies; String user; /** * Creates new form Details */ public Details() { initComponents(); } public Details(int AGE, ArrayList HOBBIES, String USER) { age = AGE; hobbies = HOBBIES; user = USER; initComponents(); }

private void formWindowOpened(java.awt.event.WindowEvent evt) { System.out.println(""+age); System.out.println(""+hobbies.get(0));

jLabel6.setText(user); jLabel7.setText(""+age); DefaultListModel list = new DefaultListModel(); for (int i =0; i < hobbies.size(); i++ ) { list.addElement(hobbies.get(i)); } jList1.setModel(list); } Note:- >You have guessed it right the back button does nothing. >System.out statements are only for testing, you can ignore them. Now run your login form again to see all the screens in action.

I have used different colors, so that you don't get confused with the variables, but if you still have any problem regarding it then the image below could help you.

Java Database Connectivity : Viewing Data // Watch a video tutorial on videos page How to establish a connection between front end and back end in just 10 Steps. In my case, front end is Java GUI(using NetBeans IDE) and back end is MySql.

Database Connectivity(JDBC)

Steps :1 Create a database in your RDBMS(MySql in this example) 2 Create a table and insert some rows. 3 Open NetBeans and create a project 4 Add 'MySql JDBC Driver' Library in your project(Right click on project icon Properties Libraries Add Library MySql JDBC Driver). 5 Create a new JFrameForm under the project. 6 Insert a JTable swing component. 7 Edit it's content according to your requirement(Right click choose Table Contents). 8 Under your package and before class starts write the following codes in the source tab. import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel;

9 Insert a button to view the data when we click.Write the coding on the button's actionPerformed event. DefaultTableModel model=(DefaultTableModel) jTable1.getModel();

String sql="Select * from Table_name"; try { Class.forName("com.mysql.jdbc.Driver"); Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabasename","yourmysqlid","yourm ysqlpassword"); /*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); while (rs.next()) { String no = rs.getString("NO"); String title= rs.getString("TITLE"); String auth= rs.getString("AUTHOR"); String type= rs.getString("TYPE"); String pub= rs.getString("PUB"); String qty= rs.getString("QTY"); String amt= rs.getString("AMOUNT"); model.addRow(new Object []{ no,title,auth,type,pub,qty,amt}); } } catch(Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } 10 Change the codes in blue according to your database.

Run the file and you are done to view the contents in your database in GUI environment. Please comment if you are facing any problem.

Run View If this post helped you just give your few seconds in sharing this so that others could be he

Das könnte Ihnen auch gefallen