How to use password field as text field in Java
This post will show you how to use password field as text field in Java like this:
You must have thoughts “Why do I do this?”, “I can use text field”,…. The answer is that it is convenient. You can see it according above figure. Instead of using extra text fields, labels,… to show errors, why don’t we use itself, password field, to show errors? That helps to save space and keep UI simple.
OK, you see the purpose of this? Let’s continue.
When you type a password, you can’t see it because password field replaces your password by an another character, called by “echo char”. You can get or set the echo char by using getEchoChar() and setEchoChar() method.
By default, echo char is a black dot and you can change it to any other character you want. For example:
setEchoChar('*') //change the default echo char to '*' character
Now, you understand how it works but how to hide the echo char and show what you type. It’s very simple. You just need set the echo char to the blank character.
The problem is solved.
However, there is still an other problem. That is how to get the original password field back that means you don’t see what you type. I guess you can get the solution 😀 that is just saving the default echo char and reusing later.
JPasswordField pw = new JPasswordField(10); char defaultEchoChar = pw.getEchoChar(); //back up the default echo char ... pw.setEchoChar(''); //delete echo char - show what you type ... pw.setEchoChar(defaultEchoChar); //restore the default echo char