Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Example Java Swing Java Password Field

Related Tutorials


 
 

Share on Google+Share on Google+

Java Password Field

Advertisement
In this section we will discuss how to use password field in Java.

Java Password Field

In this section we will discuss how to use password field in Java.

To create a password field in Java Swing JPasswordField is used. JPasswordField is a subclass of JTextField. JPasswordField is a special type of text field which allows to enter password only. Due to the security reason characters of JPasswordField is displayed as the different characters rather than the user types and its value is stored into an array of characters.

Syntax :

public class JPasswordField extends JTextField

Constructor Detail

Constructor
Description
JPasswordField() A default constructor creates a new password field.
Syntax : public JPasswordField()
JPasswordField(Document doc, String txt, int columns) This constructor creates a new JPasswordField object with the given text storage model and the given column number.
Syntax : public JPasswordField(Document doc, String text, int columns)
JPasswordField(int columns) This constructor creates a new JPasswordField object with the given column number.
Syntax : public JPasswordField(int columns)
JPasswordField(String text) This constructor creates a new JPasswordField object that initialized with the given text.
Syntax : public JPasswordField(String text)
JPasswordField(String text, int columns) This constructor creates a new JPasswordField object that initialized with the given text and columns.
Syntax : public JPasswordField(String text, int columns)

Method Detail :

Some commonly used methods of this class are as follows :

  • echoCharIsSet() : A method which returns a boolean value 'true' if JPasswordField has a character set for echoing.

    Syntax : public boolean echoCharIsSet()
     
  • getAccessibleContext() : This method is used to get the AccessibleContext associated with the JPasswordField.

    Syntax : public AccessibleContext getAccessibleContext()
     
  • getEchoChar() : This method is used to get the character used for echoing by the JPasswordField.

    Syntax : public char getEchoChar()
     
  • getPassword() : This method is used to get the text of the JPasswordField. These text are stored in an array of characters.

    Syntax : public char[] getPassword()
     
  • paramString() : This method is used for debugging purposes, it returns a String of the JPasswordField.

    Syntax : protected String paramString()
     
  • setEchoChar(char c) : This method is used to set the character used for echoing by the JPasswordField.

    Syntax : public void setEchoChar(char c)

Example

Here we will give a simple example which will demonstrate you how to use JPasswordField. In this example we will create a user login application into which a user can login only when its name and password will be matched to the data stored into the database. In this example we will create a Java class and we will use the JPasswordField to take the input for password before creating a Java class we will create a database table and we will insert the bulk values into it.

Source Code

Create Database Table

CREATE TABLE `user` (                   
          `name` varchar(15) NOT NULL,          
          `password` varchar(15) DEFAULT NULL,  
          PRIMARY KEY (`name`)                  
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1

SwingJPasswordExample.java

package net.roseindia.swingExample;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;

import java.awt.event.*;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;

public class SwingJPasswordExample implements ActionListener{

	String dbName = "record";
	String driver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://localhost:3306/"+dbName;
	String user = "root";
	String password = "root";
	
	char[] inputPassword;
	
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	
	JFrame frame;
	JLabel l_pw, l_text;
	JButton button;
	JPasswordField pw;
	JTextField name_text;
	public void createUI()
	{
		frame = new JFrame("Secure Password Example");		
		frame.setLayout(null);
		
		l_text = new JLabel("Enter Name");
		name_text = new JTextField(10);
		l_pw = new JLabel("Enter Password");		
		pw = new JPasswordField(10);
		pw.setEchoChar('*');
		button = new JButton("Enter");
		button.addActionListener(this);
		
		l_text.setBounds(10,40,100,20);
        name_text.setBounds(120,40,100,20);
        l_pw.setBounds(10, 90, 100, 20);
        pw.setBounds(120,90,100,20);
        button.setBounds(120,120,80,20);
        
        frame.add(l_text);
        frame.add(name_text);
        frame.add(l_pw);
        frame.add(pw);
        frame.add(button);
		
		frame.setVisible(true);
		frame.setSize(400, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public void actionPerformed(ActionEvent ae)
	{
		if(ae.getSource() == button)
		{
			boolean bol = matchPassword();
			if(bol == true)
			{
				JOptionPane.showMessageDialog(frame, "Login Successfull.");
			}
			else
			{
				JOptionPane.showMessageDialog(pw, "Password not matched." +
					" Try again.", "Error Message", JOptionPane.ERROR_MESSAGE);
				//Zero out the possible password, for security.
				Arrays.fill(inputPassword, '0');
				//select all characters in password field
				pw.selectAll();
				//reset focus on password field
				pw.requestFocusInWindow();
			}
		}
	}
	
	public boolean matchPassword()
	{
		char[] dbPassword = null;
		inputPassword = pw.getPassword();
		String name = name_text.getText();
		try
		{
			Class.forName(driver);
			con = DriverManager.getConnection(url, user, password);
			String sql = "Select name, password from user where name = '"+name+"'";
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next())
			{
				String psw = rs.getString("password");
				dbPassword = psw.toCharArray();
			}
		}
		catch(Exception e)
		{
		  JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
				  JOptionPane.ERROR_MESSAGE);
		 }		
		if(inputPassword.length != dbPassword.length)
		{
			return false;
		}
		else
			return Arrays.equals(inputPassword, dbPassword);
	}
	public static void main(String args[])
	{
		SwingJPasswordExample sje = new SwingJPasswordExample();
		sje.createUI();
	}
}

Output

When you will execute the above example you will get the following output :

Data in the database table is as follows :

1. When you will execute this Java code then the output will be as follows :

2. When you will enter the correct value, for example, name = "deepak" and passwod= "deepak" as in the database table and then if you will click on the Enter button then the output will be as follows :

3. But, when you will enter the wrong entry in either of the text field or password field and then if you click on the Enter button then the output will be as follows :

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 1, 2013

Related Tutorials

Discuss: Java Password Field  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com