Creating a password field

Use the Swing class JPasswordField, a text component that doesn’t display the characters as they are typed in but replaces them by an asterix (‘*’). The echoed character that replaces the typed character can be set using the method setEchoChar. Notice that the method getText is deprecated as it makes use of Strings. The more secure way to get the password is through the 1.2 method getPassword that returns a character array.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new GridLayout(2, 2));
 
      final JPasswordField passwordField = new JPasswordField(20);
      final JTextField textField = new JTextField(20);
      getContentPane().add(new JLabel("User: "));
      getContentPane().add(textField);
      getContentPane().add(new JLabel("Password: "));
      getContentPane().add(passwordField);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.out.println("User: " + textField.getText());
            System.out.println("Password: " + passwordField.getPassword());
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}