JTextField JPasswordField Example Java

JPasswordField text is implicitly encrypted which takes extra code in AWT TextField.

JTextField and JPasswordField are used to take keyboard input from the user or a programmer can display some text (message) to the user. The limitation of JTextField component is it displays a single line of editable text, using a single font and a single color. Horizontal alignment of either LEFT, CENTER OR RIGHT can be specified for the text in JTextField (unlike TextField of AWT) .

A text field's preferred width (or size) can be set by specifying the number of columns(but, ultimate deciding authority is Layout manager, which you learnt in AWT).

Swing package contains JPasswordField (does not exist in AWT) class which displays each letter typed as '*' by default. The asterisk is called as an echo character which can be changed to the user's choice as in the following JPasswordField code.

import javax.swing.*;   
import java.awt.*;  
import java.awt.event.*;   
public class TextAndPass1 extends JFrame
  JTextField jfield ;
  JPasswordField pfield ;
  public TextAndPass1( )   
    Container c = getContentPane();   // default layout manager BorderLayout of Container is used
     jfield = new JTextField();
     jfield.setText("This is JTextField");
     jfield.setHorizontalAlignment( JTextField.RIGHT ) ;   
     c.add(jfield, "North");

     pfield = new JPasswordField(10);                                            
     pfield.setBackground(Color.orange );
     c.add(pfield, "South");

    setSize(350, 300);    
  public static void main(String args[])
    new TextAndPass1();


jfield = new JTextField();
jfield.setText(“This is JTextField”);

In the above code, 30 gives the size of the text field; that is, at a time we can see 30 characters and the extra characters entered by the user can be seen using arrow keys. The above three statements can be replaced with a single statement as follows.

jfield = new JTextField(“This is JTextField”, 30);

Unlike in Java AWT TextField, the text in the JTextField can be aligned. In the following statement, the text is right aligned.


The default echo character in JPasswordField is ' * ' and can be changed to any other character using setEchoChar(char) method.


In the above statement, whatever is typed in pfield is echoed as @. It is to protect the password from reading by others.

On JTextField and JPasswordField two programs exist:

Leave a Comment

Your email address will not be published.