JPasswordField is a Java SWING control used to manage password fields. Rather than use a normal JTextField it masks the characters typed by the user with some other character (default is an ‘*’).

Very often it’s useful to see the actual text in this field. One way to do this is to give the user the option to have a quick peek behind the masked characters by clicking on a checkbox. After adding this feature to UPM I thought it might share it since it used a feature of JPasswordField I hadn’t seen before.

The code below shows the action listener I placed on the checkbox used to toggle the password visibility.

hidePasswordCheckbox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            httpProxyPassword.setEchoChar('*');
        } else {
             httpProxyPassword.setEchoChar((char) 0);
        }
    }
});

Basically the setEchoChar() method sets the character that’s displayed instead of the actual character. When you set this value to “0” JPasswordField doesn’t perform any masking. It’s that simple.