问题
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.
回答1:
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.
回答2:
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
}
来源:https://stackoverflow.com/questions/13995986/compare-two-jpasswordfields-in-java-before-saving