My program takes user name and password authentication from user before initialising the program, so i created a button login to which i associated ActionListener as show below
login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(txtUserName.getText().equals("Suraj") && (txtPwd.getPassword().toString()).equals("s123")){
dispose();
TimeFrame tFrame = new TimeFrame(userName);
tFrame.setVisible(true);
tFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
tFrame.setLayout(new GridLayout());
} else {
JOptionPane.showMessageDialog(null,"User name or password don't match","Acces Denied", JOptionPane.ERROR_MESSAGE);
}
Now the problem that occurs is even if i enter correct password, program displays an error message
getPassword()
returns achar[]
. ThetoString()
on it does not return the contents as a string as you assume.Try
new String(txtPwd.getPassword()).equals("s123")
.However, there is a reason it is a
char[]
and not a String. Try looking up the security aspect of it in the javadoc.I had the same problem:
Note: this should have been a comment but is way too long for this. Consider giving the upvotes to the answers in the linked thread
As already indicated by mKorbel there is a rather complete discussion in getText() vs getPassword() .
Further, read the Swing tutorial about
JPasswordField
which contains a nice example on how you should compare the password (by comparing char arrays, and not by converting the char array to aString
) - small copy paste from the tutorial:The reason why you should compare char arrays is nicely explained by Hovercraft Full Of Eels in his answer in the linked SO question at the start of this answer.