Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide/Show Password in a JTextFIeld (Java Swing)

So I've been working on a Password Strength Checker and the way it works is that the user enters some random text into a textfield and then instantaneous visual feedback (breakdown of points) is displayed. I've also added a checkbox, which on being selected, should hide the password i.e. replace all the chars with asterisks, while preserving the actual text input by the user. A document listener is being used to keep track of changes inside the textfield. (each char on entry gets analyzed and then scored)

So, my question is, how exactly do I mask the user input with asterisks preserving its original value?

Here's what the GUI looks like:

http://speedcap.net/sharing/screen.php?id=files/51/2f/512f9abb3f92a25add7c593e9d80e9e4.png

like image 604
Manas Bajaj Avatar asked Nov 03 '13 16:11

Manas Bajaj


People also ask

How do we make the password field visible in Java?

Use jPasswordField1. setEchoChar('*') to mask the password characters with * . If you wish to see the value you are inserting use jPasswordField1. setEchoChar((char)0); Setting a value of 0 indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField .

How do I show text in JPasswordField?

By default, the echo character is the asterisk(*). The important methods of JPasswordField are get password(), getText(), getAccessibleContext() and etc. By default, JPasswordField can show the echo characters. We can hide the echo characters and show the original text to the use by click on JCheckBox.

How can we make JTextField accept only numbers in Java?

txtAnswer. addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int key = e. getKeyCode(); /* Restrict input to only integers */ if (key < 96 && key > 105) e. setKeyChar(''); }; });


1 Answers

How exactly do I mask the user input with asterisks preserving its original value?

Use the JPasswordField which has nice function jPasswordField.getPassword(); to get the password as char[] to work with.

  • Use jPasswordField1.setEchoChar('*') to mask the password characters with *.
  • If you wish to see the value you are inserting use jPasswordField1.setEchoChar((char)0); Setting a value of 0 indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField.

Tutorial and Reference:

  1. How to use Password Fields
  2. setEchoChar(char)
like image 167
Sage Avatar answered Sep 21 '22 18:09

Sage