Simple way to have a hybrid JTextField / JPasswordField?
I am developing a simple applet that has a simpe sign-in interface.
And to be concise in space, I have two JTextFields for username and password, which I also use as labels. i.e. to start with, the username JTextField will be pre-filled with grey text saying "username" and the password JTextField pre-filled with "simple password".
Then as soon as the JTextField gets focus, i cle开发者_如何学运维ar the prefill text and set the text color to black. Similar to stackoverflow's search box, but in swing.
Now for security, I would like to mask the password field when the password JTextField gets focus (but of course still have the pre-filled text legible to start with). JPasswordField doesn't allow the toggling of mask/unmask.
Any ideas for a simple way to obtain this functionality in my simple applet?
You can disable the masking echo character with setEchoChar((char)0); as stated in the JavaDoc.
An example
final JPasswordField pass = new JPasswordField("Password");
Font passFont = user.getFont();
pass.setFont(passFont.deriveFont(Font.ITALIC));
pass.setForeground(Color.GRAY);
pass.setPreferredSize(new Dimension(150, 20));
pass.setEchoChar((char)0);
pass.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
pass.setEchoChar('*');
if (pass.getText().equals("Password")) {
pass.setText("");
}
}
public void focusLost(FocusEvent e) {
if ("".equalsIgnoreCase(pass.getText().trim())) {
pass.setEchoChar((char)0);
pass.setText("Password");
}
}});
Greetz, GHad
The Text Prompt class will support a password field.
精彩评论