Java


Java Tutorial


Admission Enquiry Form

  

Java Swing JPasswordField

Java Swing JPasswordField

The JPasswordField class creates a text field that can use a character to obscure(hide) input.The JPasswordField class is a subclass of JTextField.

Constructors used with JPasswordField

Type of Constructor Constructor Description
JPasswordField()Thismethod creates a new TextField with no text and columns.
JTextField(String text)This method creates a new TextField which is initialized with the specified text.
JTextField(int columns)This method creates a new TextField without text but with the specified number of columns. .
JTextField(String text, int columns)This method creates a new TextField which is initialized with the specified text and specified number of columns.



The following example to creates an object of JPasswordField.

Example

JPasswordField txt_pass=new JPasswordField();

Example of JPasswordField with JPasswordField() constructor:

import javax.swing.*;
import java.awt.*;

class PasswordFieldEx extends JFrame
{
JLabel lbl1;
JPasswordField pass;
public PasswordFieldEx()
{
lbl1=new JLabel("Enter Password: ");
lbl1.setBounds(10, 50, 120, 20);
add(lbl1);
pass=new JPasswordField();
pass.setEchoChar('*');
pass.setBounds(120, 50, 100, 20);
add(pass);
setLayout(null);
setSize(350,300);

setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class PasswordExample1
{
public static void main(String[] args)
{
PasswordFieldEx txt_pass=new PasswordFieldEx();
}
}



Output:

The code above will display :



Example of Java Swing JPasswordField with ActionListener:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

 class PasswordFieldEx1 extends JFrame implements ActionListener
{
JLabel lbl1,lbl2;
JTextField txt;
JButton btn;
String str=new String();
JPasswordField pass;

    public PasswordFieldEx1()
{
lbl1=new JLabel("Enter Password:  ");
lbl2=new JLabel("Your Password is:");
lbl1.setBounds(10, 50, 120, 20);
lbl2.setBounds(10, 80, 120, 20);
add(lbl1);
add(lbl2);
pass=new JPasswordField();
pass.setBounds(120, 50, 100, 20);
add(pass);
txt=new JTextField();
txt.setBounds(120, 80, 100, 20);
add(txt);
btn=new JButton("Get Password");
btn.setBounds(100, 110, 120, 30);
add(btn);
btn.addActionListener(this);
setLayout(null);
setSize(350,300);
setTitle("Password Field Example");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btn)
{
str= String.valueOf(pass.getPassword());
txt.setText(str);
pass.setEchoChar('*');
}
}
}
public class PasswordFieldExample
{
public static void main(String[] args)
{
PasswordFieldEx1 txt_pass=new PasswordFieldEx1();
}
}



Output:

The code above will display :