javaswingdocumentlistener

keep jButton grey until jTextFields != null


I have 4 jTextFields that I save the input to a file once a submit button is pressed. I want to be able to keep the submit button disabled until each field is at least not null. Where can i put something like this

    if(jTextField1 == null || jTextField2 == null || jTextField3 == null || jTextField4 == null){
        jButton2.setEnabled(false);
    }

so that the program will enable/disable the button live. Like once the last field even has 1 character in it I want it to be enabled?


Solution

  • You need to add listeners to detect when the user enters text. In order to have it register any change (and not just when the user hits Enter) you should attach a DocumentListener to the underlying document of each JTextField.

    Then, have each listener call a function to do your check and update the JButton's enabled status accordingly.

    Related