Search code examples
javaswingjbuttonenable-if

Unlock JButton as fields have text


As the topic suggests I want to unlock(setEnabled(true)) my JButton register when the other fields have any text but I don't know what type of listener is this. I upload an image for clearer understanding. http://postimg.org/image/ab8alz44d/


Solution

  • add a document listener for each text field.

    void init() {
      //construct text fields
      ...
      // add listeners
      textField1.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
          checkUnlock();
        }
        public void removeUpdate(DocumentEvent e) {
          checkUnlock();
        } 
        public void insertUpdate(DocumentEvent e) {
          checkUnlock();
        });
    
       // repeat for each textfield
    }
    ...
    private void checkUnlock() {
      boolean unlock = !(textField1.getText().equals("")) && !(textField2.getText().equals("")); // ... and so on
      yourButton.setEnabled(unlock);
    }