Search code examples
javaswingactionlistenerjtextfieldnetbeans-8.1

How can I validate user input once they click tab key or click on another field?


I am Trying to to create an actionListener For jTextField Using Netbeans 8.1. I did the Following: created the textfield then right Click > Events> Action > ActionPerformed.
It Built for me the following code:

jTextField1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
          jTextField1ActionPerformed(evt);
      }
});

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
   jTextField1.setText("Box1");
} 

but it is not working! I have tried to manually code it but still didn't work.

FYI: ActionListener for CheckBox and Radio buttons-in the same panel- are working fine, but non of the text fields!


Solution

  • Use focus change listeners, in case you want to check after tab clicked or another field.

    jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
              //this will be called on tab i.e when the field looses focus
                  jTextField1FocusLost(evt);
            }
        });
    
    private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {                                    
        jTextField1.setText("Box1");
    }
    

    you can use InputVerifier also as suggested by @MadProgrammer