Search code examples
javamethodspasswordsjoptionpane

How can I set a password in JOptionPane password?


Is there a way I can change this so that when the user enters a password, it's either right or wrong. Forexample, if the correct password is "water" then how would I do that so that if it's "water" the answer is right, otherwise if not, it's wrong.

{
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter a password:");
JPasswordField pass = new JPasswordField(10);
panel.add(label);
panel.add(pass);
String[] options = new String[]{"OK", "Cancel"};
int option = JOptionPane.showOptionDialog(null, panel, "The title",
                                          JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
                                          null, options, options[0]);
if(option == 0) // pressing OK button
 {
  char[] password = pass.getPassword();
  System.out.println("Your password is: " + new String(password));
 }
 }

Any help would be greatly appreciated! Thank you!


Solution

  • Well, you get the password-string by new String(password). You can compare that string to "water". Keep in mind that you have to use .Equals to compare strings.