How to set Echo Char for JPasswordField in Java?



With echo char, you can set a character that would appear whenever a user will type the password in the JPasswordField.

Let us first create a new JPassword field −

JPasswordField passwd = new JPasswordField();

Now, use the setEchoChar() to set the echo char for password field. Here, we have asterisk (*) as the field for password −

passwd.setEchoChar('*');

The following is an example to set echo char for password field −

Example

package my; 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 SwingDemo {    public static void main(String[] args) throws Exception {       JFrame frame = new JFrame("Register!");       JLabel label1, label2, label3;       frame.setLayout(new GridLayout(2, 2));       label1 = new JLabel("Id", SwingConstants.CENTER);       label2 = new JLabel("Age", SwingConstants.CENTER);       label3 = new JLabel("Password", SwingConstants.CENTER);       JTextField emailId = new JTextField(20);       JTextField age = new JTextField(20);       JPasswordField passwd = new JPasswordField();       passwd.setEchoChar('*');       frame.add(label1);       frame.add(label2);       frame.add(label3);       frame.add(emailId);       frame.add(age);       frame.add(passwd);       frame.setSize(550,250);       frame.setVisible(true);    } }

Output

Updated on: 2019-07-30T22:30:26+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements