Fleshing out my comment to @Mad's answer:
[invoking button.doClick()
] is not the best of solutions because it introduces an unnecessary coupling between several views Instead, use one Action and set it to both the textField and the button
The advantages:
- (as already noted): no coupling between views
- a single location to implement the login logic
- has the notion of enabled, so can be disabled - and with it all views it is bound to . on a locked login
A raw (taking a bit too much responsibility, further separation strongly advised) code snippet, taking over
- grab the valid pins
- register the documentFilter
- validate/lock the login
The Action:
public static class LoginAction extends AbstractAction {
private final AtomicInteger nbTry = new AtomicInteger(0);
private ArrayList<Integer> pins = readPinsData(new File("bdd.txt"));
private Document doc;
public LoginAction(String login, AbstractDocument doc) {
super(login);
this.doc = doc;
doc.setDocumentFilter(new DocumentFilter(){
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String string =fb.getDocument().getText(0, fb.getDocument().getLength())+text;
if(string.length() <= 4)
super.replace(fb, offset, length, text, attrs);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
if (nbTry.get() > 2) {
JOptionPane.showMessageDialog(null,
"Pin blocked due to 3 wrong tries");
setEnabled(false);
return;
}
String passEntered = null;
try {
passEntered = doc.getText(0, doc.getLength()).replaceAll("\u00A0", "");
} catch (BadLocationException e1) {
e1.printStackTrace();
}
if (passEntered.length() != 4) {
JOptionPane.showMessageDialog(null, "Pin must be 4 digits");
return;
}
boolean authenticated = false;
ImageIcon imgAngry = new ImageIcon("angry.png");
ImageIcon imgHappy = new ImageIcon("happy.png");
if (pins.contains(Integer.parseInt(passEntered))) {
JOptionPane.showMessageDialog(null, "Pin correct", "Good Pin", JOptionPane.INFORMATION_MESSAGE, imgHappy);
authenticated = true;
}
if (!authenticated) {
JOptionPane.showMessageDialog(null, "Wrong Pin", "Wrong Pin", JOptionPane.INFORMATION_MESSAGE, imgAngry);
nbTry.incrementAndGet();
}
}
}
It's usage:
PlainDocument document =(PlainDocument)passwordField.getDocument();
LoginAction action = new LoginAction("OK", document);
passwordField.setAction(action);
loginButton.setAction(action);