Java Swing How to - Set Echo Char for JPasswordField








Question

We would like to know how to set Echo Char for JPasswordField.

Answer

//  w  w w  .  j a v a  2s. c  o  m
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setLayout(new GridLayout(2, 2));
    JLabel label = new JLabel("User Name:", SwingConstants.RIGHT);
    JLabel label2 = new JLabel("Password:", SwingConstants.RIGHT);
    JTextField userNameField = new JTextField(20);

    JPasswordField passwordField = new JPasswordField();
    passwordField.setEchoChar('#');

    frame.add(label);
    frame.add(userNameField);
    frame.add(label2);
    frame.add(passwordField);
    frame.setSize(200, 70);
    frame.setVisible(true);
  }
}