Validate a password entered in a JPasswordField - Java Swing

Java examples for Swing:JPasswordField

Introduction

The following snippet of code shows how to validate a password entered in a JPasswordField:

Demo Code

import java.util.Arrays;

import javax.swing.JPasswordField;

public class Main {

  public static void main(String[] args) {
    JPasswordField passwordField = new JPasswordField(10);
    char c[] = passwordField.getPassword();
    String correctPass = "Hello";
    char[] cp = correctPass.toCharArray();

    if (Arrays.equals(c, cp)) {
      // The password is correct
    } else {/*from  ww  w. ja v  a2s  . co m*/
      // The password is incorrect
    }
    Arrays.fill(c, (char) 0);
    Arrays.fill(cp, (char) 0);
  }
}

Related Tutorials