Based on JTextField content, enable or disable a JButton

From CodeCodex

Implementations[edit]

Java[edit]

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;


public class DemoJButtonDisabled extends JApplet {
  JButton button;
  JTextField textfield;
  Document document;
  public void init() {
    getContentPane().setLayout(new FlowLayout());
    textfield = new JTextField(10);
    getContentPane().add(textfield);
    button = new JButton("foo");
    getContentPane().add(button);
    button.setEnabled(false);

    document = textfield.getDocument();
    document.addDocumentListener
     (new JButtonStateController(button));
  }
}

class JButtonStateController implements DocumentListener {
    private JButton button;

    JButtonStateController(JButton b) {
        button = b;
    }

    public void changedUpdate(DocumentEvent e) {
        disableIfEmpty(e);
    }

    public void insertUpdate(DocumentEvent e){
        disableIfEmpty(e);
    }

    public void removeUpdate(DocumentEvent e){
        disableIfEmpty(e);
    }

    public void disableIfEmpty(DocumentEvent e) {
        button.setEnabled(e.getDocument().getLength() > 0);
    }
}