3

I have a JTextField. The same JTextField will be used to get both name and password of the user. So if it's getting the username, I would display what the user is typing on the Text field. But if he's inserting a password, the field should not display the password (but display * characters instead).

How can I make a JTextField hide the characters that he/she types ?

Pseudocode :

If (usernameBool!=true) {
 // Display normal text - user is able to see the password
} else {
// This is going to be a password field, so i need to not show the password to the user instead show it as ******* instead.

}

Note: I don't want to use JPasswordField for this

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140
  • 2
    "I don't want to use JPasswordField for this" And why exactly? – Cubic Dec 15 '12 at 15:35
  • Can you explain why you want to be the same exact obect? The fact that in the GUI you will have just one field doesn't mean you can't use a `JPasswordField` that just exists for this. You can safely change the underlying field and switch between the two. – Jack Dec 15 '12 at 15:36
  • 1
    Because i am using the same JTextField to get the username and password. and i don't want to add any other field – Sharon Watinsan Dec 15 '12 at 15:36
  • 2
    "I don't want". So you prefer writing something awkward and spending time for it without any reason? That's not a good point. – Jack Dec 15 '12 at 15:37
  • @sharonHwk: but please explain the *whys* behind this decision. Perhaps we can help you solve this better if you tell us more detail. For instance, if the key is that you want the location of name and password entry to be the same exact spot on the GUI, then perhaps a CardLayout will let you swap a JTextField for a JPasswordField. – Hovercraft Full Of Eels Dec 15 '12 at 15:38
  • @HovercraftFullOfEels I am using a singe frame for authentication. So i will have to take both username and password fileds from this frame. And, i can't change the structure of this frame. (i can't remove the existing JTextField and add a JPasswordField) – Sharon Watinsan Dec 15 '12 at 15:40
  • 1
    Pop a `JOptionPane` with both components as seen [here](http://stackoverflow.com/a/10773412/418556). – Andrew Thompson Dec 15 '12 at 15:43
  • 2
    I just don't understand why this post is downvoted. It's a valid question, and none seems to know the answer. So is that why it's downvoted ? – Sharon Watinsan Dec 15 '12 at 15:44
  • I gave it a -1 because 1) It is a silly requirement (use an insecure component for a password), combined with 2) A facile reason for not using the correct component. P.S. I also threw in a vote to close as 'not a real question'. – Andrew Thompson Dec 15 '12 at 15:46
  • 1
    @Sharon: It was likely down voted since it was very incomplete to start with and was difficult to get information out of you necessary to allow us to answer the question. Not my down vote by the way. – Hovercraft Full Of Eels Dec 15 '12 at 15:50

4 Answers4

6

Again, one possible solution is to use a CardLayout to swap components:

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.*;

public class SwapFields {
   private static final String TEXT_FIELD = "text field";
   private static final String PASS_FIELD = "pass field";

   public SwapFields() {
      // TODO Auto-generated constructor stub
   }

   private static void createAndShowGui() {
      final JTextField textField = new JTextField(10);
      final JPasswordField passwordField = new JPasswordField(10);

      final CardLayout cardLayout = new CardLayout();
      final JPanel cardPanel = new JPanel(cardLayout);
      cardPanel.add(textField, TEXT_FIELD);
      cardPanel.add(passwordField, PASS_FIELD);

      JToggleButton toggleBtn = new JToggleButton("Entering Password");
      toggleBtn.addItemListener(new ItemListener() {

         @Override
         public void itemStateChanged(ItemEvent iEvt) {
            if (iEvt.getStateChange() == ItemEvent.SELECTED) {
               cardLayout.show(cardPanel, PASS_FIELD);
               passwordField.requestFocusInWindow();
            } else {
               cardLayout.show(cardPanel, TEXT_FIELD);
               textField.requestFocusInWindow();
            }
         }
      });

      JButton showNamePasswordBtn = new JButton("Show Results");
      showNamePasswordBtn.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            System.out.println("Name: " + textField.getText());

            // never do this!
            System.out.println("Pass: " + new String(passwordField.getPassword()));
         }
      });

      JPanel mainPanel = new JPanel();
      mainPanel.add(cardPanel);
      mainPanel.add(toggleBtn);
      mainPanel.add(showNamePasswordBtn);

      JFrame frame = new JFrame("SwapFields");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
5

The JPasswordField has a method which is setEchoChar(). As documentation states:

Sets the echo character for this JPasswordField. ... 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.

You can then use just a JPasswordField and enable the echo character (eg. '*') just for the password.

Jack
  • 131,802
  • 30
  • 241
  • 343
2

I suggest you use a JPasswordField. Then when your usernameBool is true, set it to show the characters, but otherwise hide the characters, like this:

if (usernameBool) {
     password.setEchoChar((char) 0);
} else {
     password.setEchoChar('*');
}
Clark
  • 1,357
  • 1
  • 7
  • 18
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
-1

You can create your own JTextField which your own strategy. For example, you can keep the last character (like iOS if i remember) or don't show anything (Linux style).

bob
  • 1
  • 1