1

Possible Duplicate:
How to check if JPassword field is null

While creating a login registration form, I am using two password fields. Before saving the data, I want to compare both fields; and if they match, then the data should be saved in file. If not it should open a dialog box. Please can anyone help me.

Community
  • 1
  • 1
user1922355
  • 39
  • 2
  • 4
  • 12
  • 5
    What have you tried so far? Please show some effort before posting. I bet if you got the text from both password fields and compared them that would be a good start. – Nate W. Dec 21 '12 at 19:30

2 Answers2

11

The safest way would be to use Arrays.equals:

if (Arrays.equals(passwordField1.getPassword(), passwordField2.getPassword())) {
   // save data
} else {
  // do other stuff
}

Explanation: JPassword.getText was purposely deprecated to avoid using Strings in favor of using a char[] returned by getPassword.

When calling getText you get a String (immutable object) that may not be changed (except reflection) and so the password stays in the memory until garbage collected.

A char array however may be modified, so the password will really not stay in memory.

This above solution is in keeping with that approach.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
3

It would help to show what you have tried...

but you'd do it something like:

//declare fields

JPasswordField jpf1=...;
JPasswordField jpf2=...;

...

 //get the password  from the passwordfields

String jpf1Text=Arrays.toString(jpf1.getPassword());//get the char array of password and convert to string represenation
String jpf2Text=Arrays.toString(jpf2.getPassword());

//compare the fields contents
if(jpf1Text.equals(jpf2Text)) {//they are equal

}else {//they are not equal

}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138