0

I have small Java GUI program (screenshot below). One of the values is "Passport Number".

This field should contain 11 symbols. Once the user has entered a value in this field, I want to check the correct number of symbols are in place and set string "error" in Label item "Label1" if not.

I tried this:

private void btnSendActionPerformed(java.awt.event.ActionEvent evt) { 
   String error;                                       
   if(passportn.length()!=11) {
     error="error";
     label1.setText(error);
   }
 }                       

This works but only when a button is pressed. Instead I want this to happen as the user enters passport number.

screenshot

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Nika Tsogiaidze
  • 949
  • 14
  • 18
  • 1
    I think you can find your answer at a similar post http://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield – Orel Eraki Dec 05 '13 at 11:04

2 Answers2

2

1) You can use InputVerifier like next :

final JLabel l = new JLabel(" ");
JTextField field = new JTextField();
field.setInputVerifier(new InputVerifier() {

    @Override
    public boolean verify(JComponent arg0) {
        Boolean b = ((JTextField)arg0).getText().length() == 11;
        if(!b){
            l.setText("error");
        } else {
            l.setText("accepted");
        }
        return b;
    }
});

with that before you enter 11 characters you cant to set focus to another component.

2) Use DocumentListener, for example :

final JLabel l = new JLabel(" ");

JTextField field = new JTextField();
field.getDocument().addDocumentListener(new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent arg0) {
        validate(arg0);
    }

    @Override
    public void insertUpdate(DocumentEvent arg0) {
        validate(arg0);
    }

    @Override
    public void changedUpdate(DocumentEvent arg0) {
        validate(arg0);
    }

    private void validate(DocumentEvent arg0){
        Boolean b = arg0.getDocument().getLength() == 11;
        if (!b) {
            l.setText("error");
        } else {
            l.setText("accepted");
        }
    }
});

In that case DcumentListener will validate each character entered or removed, and then change text in JLabel.

alex2410
  • 10,904
  • 3
  • 25
  • 41
0

You can do this using a JFormattedText field, there is a full tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

and javadoc here: http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html

But in brief it is a way of setting up a text field and then specifying what the allowed data within that text field are and also what to do when someone tries to enter invalid data.

Tim B
  • 40,716
  • 16
  • 83
  • 128