tags:

views:

54

answers:

2

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 clear 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?

+3  A: 

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

GHad
bad on me for not reading the javadoc completely! i looked at its code, even extended it, but never bothered to read the javadoc for setEchoChar! Thanks GHad!
Patrick
+1  A: 

The Text Prompt class will support a password field.

camickr