-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathInputPassword.java
More file actions
81 lines (59 loc) · 1.96 KB
/
InputPassword.java
File metadata and controls
81 lines (59 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package gui;
/**
* RUN:
* javac -cp .; gui/InputPassword.java && java -cp .; gui.InputPassword
* OUTPUT:
*
*/
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import net.mindview.util.*;
public class InputPassword extends JFrame {
private static final int WIDTH = 400;
private static final int HEIHGT = 250;
private char[] correctPassword = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
private JPasswordField pwd = new JPasswordField(15);
private ActionListener pwdListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
char[] input = pwd.getPassword();
if (isPasswordCorrect(input)) {
JOptionPane.showMessageDialog(InputPassword.this,
"Success! You typed the right password.");
} else {
JOptionPane.showMessageDialog(InputPassword.this,
"Invalid password. Try again.",
"Error Message",
JOptionPane.ERROR_MESSAGE);
}
//Zero out the possible password, for security.
Arrays.fill(input, '0');
pwd.selectAll();
resetFocus();
}
};
private boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals(input, correctPassword);
}
return isCorrect;
}
protected void resetFocus() {
pwd.requestFocusInWindow();
}
public InputPassword() {
setLayout(new FlowLayout());
JLabel label = new JLabel("Enter password");
add(label);
add(pwd);
pwd.addActionListener(pwdListener);
}
public static void main(String[] args) {
SwingConsole.run(new InputPassword(), WIDTH, HEIHGT);
}
}