I followed this Oracles tutorial about JPasswordField and I created a simple demo application:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
public class JPasswordFieldDemo {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPasswordField passwordField = new JPasswordField(20);
JButton button = new JButton("Login");
public JPasswordFieldDemo() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
char[] input = passwordField.getPassword();
if (performCheck(input)) {
JOptionPane.showMessageDialog(null, "Correct password");
} else {
JOptionPane.showMessageDialog(null, "Incorrect password");
}
}
});
passwordField.setEchoChar('*');
panel.add(passwordField);
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private boolean performCheck(char[] input) {
boolean isCorrect = false;
char[] correctPass = { '1', '2', '3' };
if (input.length != correctPass.length) {
isCorrect = false;
}
if (Arrays.equals(input, correctPass)) {
isCorrect = true;
}
Arrays.fill(correctPass, '0');
return isCorrect;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JPasswordFieldDemo();
}
});
}
}
Now, the part that confuses me is in performCheck
method. My question is:
Is there a any good reason why should I compare lengths of two char arrays (as they did in their tutorial)?
Or my method can look like this too:
private boolean performCheck(char[] input) {
boolean isCorrect = false;
char[] correctPass = { '1', '2', '3' };
if (Arrays.equals(input, correctPass)) {
isCorrect = true;
}
Arrays.fill(correctPass, '0');
return isCorrect;
}
Regards, and thanks in advance.
Your example does not reflect the predicate shown in the tutorial, which checks the length first and then checks the content only if the lengths match. Arrays of unequal length can never be equal.
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}