Reputation: 9969
getPassword() gives me an array of chars, but I want the password which looks like this ******
to shows up like this MyPaSwOrd
, how can I do that ?
Guys I don't wanna extract the password, I just wanna write like " Enter your Password " inside the JPasswordField(), and when the user clicks on it, this goes away, and then he types his own password, which is like this * * * * * *
Upvotes: 3
Views: 2695
Reputation: 738
Dirty Way
make one passwordfield and a text field... When you check the box, passwordField will be made invisible and textbox visible.
while in the unchecked condition, passwordField will be visible and textfield invisible.
and finally, make the textfield to copy the text entered in passwordField.
Upvotes: 0
Reputation: 31603
two ways:
EDIT:
If you want to have a text like "Enter PW" in your field that disappears on a click, then try something like this:
public class JPassword {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JPasswordField field = new JPasswordField();
field.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent arg0) {
char c = 0;
field.setEchoChar(c);
field.setText("Enter PW");
}
@Override
public void focusGained(FocusEvent arg0) {
char c = 1;
field.setEchoChar(c);
field.setText("");
}
});
char c = 0;
field.setText("Enter PW");
field.setEchoChar(c);
frame.setLayout(new FlowLayout());
frame.getContentPane().add(new JButton("test"));
frame.getContentPane().add(field);
frame.pack();
frame.setVisible(true);
}
}
Note: You need to check whether the user has entered a password or not. If he had, don't execute the focuseGained method. Otherwise the password will disappear. But this shouldn't be a problem.
Upvotes: 1
Reputation: 8230
Try this:
String password = new String(passwordField.getText());
However, the documentation explicitly states that you shouldn't be using Strings for checking/manipulating/passing password information.
This explains how to check char[] passwords.
EDIT :
You can have an ordinary JField
with "Enter here your password" as its text
and put a click listener
on it. whenever a user clicks on it, remove the JTextField
and replace it with JPassword
wih having the focus
Upvotes: 1